﻿using System;
using System.Collections.Generic;
using System.Net;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data;
using System.Web.UI.HtmlControls;
using System.Collections;
using Newtonsoft.Json;
using System.Linq;

using CE.Skyscanner;
using CE.Database;
using CE.User;
using CE.Wego;
using CE.TravelInsurance;
using CE.Global;

public partial class travel_flights_results_new : System.Web.UI.Page
{
    private string locfrom = "";
    private string locto = "";
    private string outbounddate = "";
    private string inbounddate = "";
    private string noofadult = "";
    private string triptype = "";
    private string locfromname = "";
    private string loctoname = "";
    private string instanceid = "";
    private string airlines = "";
    private Int64 searchid = 0;
    private Int64 timercount = 0;

    WegoFlightsDB wegodb = new WegoFlightsDB();
    WegoFlights myflight = new WegoFlights();

    protected void Page_Load(object sender, EventArgs e)
    {
        //if (Request.QueryString["insid"] != null)
        //{
        //    instanceid = Request.QueryString["insid"];

        //    if (instanceid != null)
        //    {
                if (Session["wegosearchparams"] != null)
                {
                    string[] sessionparams = (string[])Session["wegosearchparams"];

                    locfrom = sessionparams[0].ToString();
                    locto = sessionparams[1].ToString();
                    outbounddate = sessionparams[2].ToString();
                    inbounddate = sessionparams[3].ToString();
                    noofadult = sessionparams[4].ToString();
                    triptype = sessionparams[5].ToString();
                    locfromname = sessionparams[6].ToString();
                    loctoname = sessionparams[7].ToString();


                    //set search details
                    lblLocation.Text = "Flights from " + locfromname + " to " + loctoname;

                    DateTime dtout = Convert.ToDateTime(outbounddate);
                    DateTime dtin = Convert.ToDateTime(inbounddate);
                    lblDates.Text = dtout.ToString("dd MMM yyyy") + " to " + dtin.ToString("dd MMM yyyy");

                    int FromLength = locfromname.IndexOf("(", 0) - locfromname.IndexOf(",");
                    int ToLength = loctoname.IndexOf("(", 0) - loctoname.IndexOf(",");

                    if (FromLength > 0)
                        lblFrom.Text = locfromname.Substring(locfromname.IndexOf(","), FromLength).Remove(0, 1);
                    else
                    {
                        FromLength = locfromname.IndexOf("(", locfromname.IndexOf("(", 0) + 1) - locfromname.IndexOf(",");

                        if (FromLength > 0)
                            lblFrom.Text = locfromname.Substring(locfromname.IndexOf(","), FromLength).Remove(0, 1);
                    }

                    if (ToLength > 0)
                        lblTo.Text = loctoname.Substring(loctoname.IndexOf(","), ToLength).Remove(0, 1);
                    else
                    {
                        ToLength = loctoname.IndexOf("(", loctoname.IndexOf("(", 0) + 1) - loctoname.IndexOf(",");

                        if (ToLength > 0)
                            lblTo.Text = loctoname.Substring(loctoname.IndexOf(","), ToLength).Remove(0, 1);
                    }

                    //Left Labels
                    lblLeftFrom.Text = lblFrom.Text;
                }
                else
                {
                    //Response.Redirect("flights-search.aspx");
                    Response.Redirect("~/travel-flights/");

                }
        //    }
        //    else
        //    {
        //        //Response.Redirect("flights-search.aspx");
        //        Response.Redirect("~/travel-flights/");
        //    }
        //}
        //else
        //{
        //    //Response.Redirect("flights-search.aspx");
        //    Response.Redirect("~/travel-flights/");

        //}

        Session["flightsid"] = Session[General.TAId].ToString();
        //if (Session["flightsid"] != null)
        //    searchid = Int64.Parse(Session["flightsid"].ToString());
        //else
        //{
        //    //Response.Redirect("flights-search.aspx");
        //    Response.Redirect("~/travel-flights/");
        //}

        airlines = inair.Value.ToString();

        if (!IsPostBack)
        {
            if (locfrom == "SIN")
            {
                divbanner.Visible = false;
                divtravelresults.Visible = true;

                Session[General.TAResultId] = null;
                ResultsQuotesDataBind();
                Session[General.ViewedDetailsId] = LogUserViewedHistory().ToString();
            }
            else
            {
                divbanner.Visible = true;
                divtravelresults.Visible = false;
            }

            Session["count"] = 0;
            getFlightResult_step1();
            //GetFlightResults();
            GetFlightDetails();

            userBirthday.StartYear = CE.Global.General.GetUTCDateTime().Year - 100;
            userBirthday.EndYear = CE.Global.General.GetUTCDateTime().Year - 18;

            lnkbtnChange.Attributes.Add("OnClick", "javascript:return confirm('Go back to search page?'); return false;");
            btnBack.Attributes.Add("OnClick", "javascript:return confirm('Go back to search page?'); return false;");

            if (Cache["FlightList"] != null)
                Cache.Remove("FlightList");
            if (Cache["FlightListFiltered"] != null)
                Cache.Remove("FlightListFiltered");
        }

        imgbtnViewSummary.Visible = false;
    }

    public int PageNumber
    {
        get
        {
            if (ViewState["PageNumber"] != null)
                return Convert.ToInt32(ViewState["PageNumber"]);
            else
                return 0;
        }
        set
        {
            ViewState["PageNumber"] = value;
        }
    }

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        rptPages.ItemCommand +=
           new RepeaterCommandEventHandler(rptPages_ItemCommand);

        rptPagesBottom.ItemCommand +=
           new RepeaterCommandEventHandler(rptPagesBottom_ItemCommand);
    }

    void rptPages_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        PageNumber = Convert.ToInt32(e.CommandArgument) - 1;

        //GetFlightDetails(searchid, airlines);
        SkyscannerDataInfo _objSkyscannerDataInfo = (SkyscannerDataInfo)Cache["FlightList"];
        if (Cache["FlightListFiltered"] != null)
            _objSkyscannerDataInfo = (SkyscannerDataInfo)Cache["FlightListFiltered"];
        GetFlightDetails(_objSkyscannerDataInfo);
    }

    void rptPagesBottom_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        PageNumber = Convert.ToInt32(e.CommandArgument) - 1;

        //GetFlightDetails(searchid, airlines);
        SkyscannerDataInfo _objSkyscannerDataInfo = (SkyscannerDataInfo)Cache["FlightList"];
        if (Cache["FlightListFiltered"] != null)
            _objSkyscannerDataInfo = (SkyscannerDataInfo)Cache["FlightListFiltered"];
        GetFlightDetails(_objSkyscannerDataInfo);
    }

    protected void rptPages_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            LinkButton lbtnPage = (LinkButton)e.Item.FindControl("btnPage");

            int pagenum = PageNumber + 1;
            if (lbtnPage.CommandArgument == pagenum.ToString())
            {
                lbtnPage.ForeColor = System.Drawing.Color.Black;
                lbtnPage.Enabled = false;
            }
        }
    }

    protected void rptPagesBottom_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            LinkButton lbtnPage = (LinkButton)e.Item.FindControl("btnPage");

            int pagenum = PageNumber + 1;
            if (lbtnPage.CommandArgument == pagenum.ToString())
            {
                lbtnPage.ForeColor = System.Drawing.Color.Black;
                lbtnPage.Enabled = false;
            }
        }
    }

    private void GetFlightResults()
    {
        //if (instanceid != null)
        if (true)
        {
            lblLocation.Text = "Flights from " + locfromname + " to " + loctoname;

            DateTime dtout = Convert.ToDateTime(outbounddate);
            DateTime dtin = Convert.ToDateTime(inbounddate);
            lblDates.Text = dtout.ToString("dd MMM yyyy") + " to " + dtin.ToString("dd MMM yyyy");

            int FromLength = locfromname.IndexOf("(", 0) - locfromname.IndexOf(",");
            int ToLength = loctoname.IndexOf("(", 0) - loctoname.IndexOf(",");

            if (FromLength > 0)
                lblFrom.Text = locfromname.Substring(locfromname.IndexOf(","), FromLength).Remove(0, 1);
            else
            {
                FromLength = locfromname.IndexOf("(", locfromname.IndexOf("(", 0) + 1) - locfromname.IndexOf(",");

                if (FromLength > 0)
                    lblFrom.Text = locfromname.Substring(locfromname.IndexOf(","), FromLength).Remove(0, 1);
            }

            if (ToLength > 0)
                lblTo.Text = loctoname.Substring(loctoname.IndexOf(","), ToLength).Remove(0, 1);
            else
            {
                ToLength = loctoname.IndexOf("(", loctoname.IndexOf("(", 0) + 1) - loctoname.IndexOf(",");

                if (ToLength > 0)
                    lblTo.Text = loctoname.Substring(loctoname.IndexOf(","), ToLength).Remove(0, 1);
            }

            //Left Labels
            lblLeftFrom.Text = lblFrom.Text;

            //bool isRoundtrip = false;

            //if (triptype == "roundTrip")
            //    isRoundtrip = true;

            DataTable dtSummary = new DataTable();
            DataView dvSummary = new DataView();

            CheckSession();

            if (Cache["flights" + Session["flightsid"].ToString()] == null)
            {
                //bool isDone = myflight.GetFlightResults(instanceid, isRoundtrip, outbounddate, inbounddate, searchid.ToString());
                bool isDone = true;

                if (isDone)
                {
                    dtSummary = wegodb.GetWegoSummary(searchid);
                    dvSummary = new DataView(dtSummary);

                    string strSortExpress2 = " totalPricePerPassenger ASC";
                    dvSummary.Sort = strSortExpress2;

                    Cache["flights" + Session["flightsid"].ToString()] = dvSummary.ToTable();
                    gvFlightsResults.DataSource = dvSummary;
                }
            }
            else
            {
                dtSummary = (DataTable)Cache["flights" + Session["flightsid"].ToString()];
                gvFlightsResults.DataSource = dtSummary;
            }


            gvFlightsResults.DataBind();

            //Get Total
            int flightcount = 0;

            foreach (DataRow drow in dtSummary.Rows)
            {
                flightcount = int.Parse(drow["ResultsCount"].ToString()) + flightcount;
            }

            lblCount.Text = flightcount.ToString();
            lblCountAll.Text = flightcount.ToString();


            //if (_dsResults != null && _dsResults.Tables.Count > 0)
            //{
            //DataTable _dtResult = _dsResults.Tables[0];

            ////_dtResult = RemoveSameId(_dsResults.Tables[0]);
            //DataView dv = new DataView(_dtResult);

            //DataTable _dtAirLocation = _dsResults.Tables[1];
            //DataView dvAirLoc = new DataView(_dtAirLocation);
            //ViewState["airlocation"] = dvAirLoc.ToTable();

            //string strSortExpress = "Airlines, totalPricePerPassenger ASC";
            //dv.Sort = strSortExpress;

            //DataTable dttosave = dv.ToTable();
            //Cache["flights" + Session[General.ViewedDetailsId].ToString()] = dttosave;

            //DataTable dtSummary = GetDTSummary(dv.ToTable());

            //lblCount.Text = _dtResult.Rows.Count.ToString();
            //lblCountAll.Text = _dtResult.Rows.Count.ToString();
            //}
        }

    }

    private DataTable RemoveSameId(DataTable dtListOrig)
    {
        //DataRow[] dr = payments.dtPayments.Select(myselect);

        DataView dvList = new DataView(dtListOrig);
        string strSortExpressByID = "ID, Provider ASC";
        dvList.Sort = strSortExpressByID;

        DataTable dtList = dvList.ToTable();

        DataRow[] dr = dtList.Select();
        List<DataRow> rowsToRemove = new List<DataRow>();

        string rowid = "";
        string provider = "";
        int irow = 0;

        foreach (DataRow row in dtList.Rows)
        {
            rowid = row["ID"].ToString();
            provider = row["Provider"].ToString();

            if (rowid == inid.Value && provider == inprovider.Value)
            {
                rowsToRemove.Add(dr[irow]);
            }
            else
            {
                inid.Value = rowid;
                inprovider.Value = provider;
            }

            irow++;
        }

        foreach (DataRow dr2 in rowsToRemove)
        {
            dtList.Rows.Remove(dr2);
        }

        dtList.AcceptChanges();

        return dtList;
    }

    private DataTable GetDTSummary(DataTable dtList)
    {
        DataTable dtSummary = new DataTable();

        dtSummary.Columns.Add("Airlines", System.Type.GetType("System.String"));
        dtSummary.Columns.Add("totalPricePerPassenger", System.Type.GetType("System.Double"));
        dtSummary.Columns.Add("CurrencyCode", System.Type.GetType("System.String"));
        dtSummary.Columns.Add("ResultsCount", System.Type.GetType("System.String"));
        dtSummary.Columns.Add("AirlineCode", System.Type.GetType("System.String"));

        DataRow dr;
        string airlinename = "";
        int i = 0;
        bool isAdd = false;

        string ToAddAirlines = "";
        string ToAddAirlineCode = "";
        string ToAddPrice = "";
        string ToAddCurrency = "";
        string ToAddCount = "0";

        //DataTable dtViewFilter = (DataTable)Cache["flights" + Session[General.ViewedDetailsId].ToString()];
        DataTable dtViewFilter = (DataTable)Cache["flights" + Session["flightsid"].ToString()];

        DataView dvCount = dtViewFilter.DefaultView;

        foreach (DataRow row in dtList.Rows)
        {
            airlinename = row["Airlines"].ToString();

            if (i == 0)
            {
                inair.Value = airlinename;
                isAdd = true;

                ToAddAirlines = airlinename;
                ToAddPrice = row["totalPricePerPassenger"].ToString();
                ToAddCurrency = row["CurrencyCode"].ToString();
                ToAddAirlineCode = row["AirlineCode"].ToString();

                dvCount.RowFilter = "Airlines = '" + airlinename + "' ";
                ToAddCount = dvCount.Count.ToString();
            }
            else
            {
                if (airlinename == inair.Value)
                {
                    isAdd = false;
                    //e.Row.Visible = false;
                }
                else
                {
                    inair.Value = airlinename;
                    isAdd = true;

                    ToAddAirlines = airlinename;
                    ToAddPrice = row["totalPricePerPassenger"].ToString();
                    ToAddCurrency = row["CurrencyCode"].ToString();
                    ToAddAirlineCode = row["AirlineCode"].ToString();

                    dvCount.RowFilter = "Airlines = '" + airlinename + "' ";
                    ToAddCount = dvCount.Count.ToString();
                }
            }

            if (isAdd)
            {
                dr = dtSummary.NewRow();

                dr["Airlines"] = ToAddAirlines;
                dr["totalPricePerPassenger"] = ToAddPrice;
                dr["CurrencyCode"] = ToAddCurrency;
                dr["ResultsCount"] = ToAddCount;
                dr["AirlineCode"] = ToAddAirlineCode;

                dtSummary.Rows.Add(dr);
            }

            i++;

        }



        return dtSummary;
    }

    protected void gvFlightsResults_RowDatabound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Image imgAirLogo = new Image();
            imgAirLogo = (Image)e.Row.FindControl("imgAirlineLogo");

            string _airlinecode = DataBinder.Eval(e.Row.DataItem, "AirlineCode").ToString();
            imgAirLogo.ImageUrl = "http://media.wego.com/images/flights/airlines/80x27/" + _airlinecode + ".gif";


            string _currency = "";
            string _price = "";
            string _count = "";

            Label lblCurrency = new Label();
            lblCurrency = (Label)e.Row.FindControl("lblCurrency");
            Label lblPrice = new Label();
            lblPrice = (Label)e.Row.FindControl("lblPrice");
            Label lblResultsCount = new Label();
            lblResultsCount = (Label)e.Row.FindControl("lblResultsCount");

            object _objcurrency = DataBinder.Eval(e.Row.DataItem, "CurrencyCode");
            if (_objcurrency != null)
                _currency = _objcurrency.ToString();

            object _objpriceperpassenger = DataBinder.Eval(e.Row.DataItem, "totalPricePerPassenger");
            if (_objpriceperpassenger != null)
                _price = String.Format("{0:0,0.00}", Convert.ToDouble(_objpriceperpassenger));

            lblCurrency.Text = _currency;
            lblPrice.Text = _price;


            object _objcount = DataBinder.Eval(e.Row.DataItem, "ResultsCount");
            if (_objcount != null)
                _count = _objcount.ToString();

            lblResultsCount.Text = _count + " result/s";


        }
    }

    protected void gvFlightsResults_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (gvFlightsResults.Rows.Count > 0)
        {

            airlines = gvFlightsResults.SelectedDataKey.Value.ToString();
            inair.Value = airlines;
            //old code
            //DataTable dtView = (DataTable)Cache["flights" + Session[General.ViewedDetailsId].ToString()];
            //DataView dv = dtView.DefaultView;

            //string strFilters = "Airlines = '" + Airlines + "' ";
            //dv.RowFilter = strFilters;

            //string strSortExpress = "totalPricePerPassenger ASC";
            //dv.Sort = strSortExpress;

            //rptDetails.DataSource = dv.ToTable();            

            GetFlightDetails(searchid, airlines);

        }
    }

    private void GetFlightDetails(Int64 SearchId, string Airlines)
    {
        DataTable dtDetails = SortFlights(SearchId, Airlines);

        PagedDataSource pgitems = new PagedDataSource();
        DataView dv = new DataView(dtDetails);
        pgitems.DataSource = dv;
        pgitems.AllowPaging = true;
        pgitems.PageSize = 10;
        pgitems.CurrentPageIndex = PageNumber;
        if (pgitems.PageCount > 1)
        {
            rptPages.Visible = true;
            divPaging.Visible = true;

            rptPagesBottom.Visible = true;
            divPaging2.Visible = true;

            ArrayList pages = new ArrayList();
            for (int i = 0; i < pgitems.PageCount; i++)
                pages.Add((i + 1).ToString());
            rptPages.DataSource = pages;
            rptPages.DataBind();
            rptPagesBottom.DataSource = pages;
            rptPagesBottom.DataBind();
        }
        else
        {
            rptPages.Visible = false;
            divPaging.Visible = false;

            rptPagesBottom.Visible = false;
            divPaging2.Visible = false;
        }

        rptDetails.DataSource = pgitems;

        //rptDetails.DataSource = dtDetails;
        rptDetails.DataBind();

        rptDetails.Visible = true;
        gvFlightsResults.Visible = false;

        imgbtnViewSummary.Visible = true;

        //Get Count
        CheckSession();
        //if (Cache["flights" + Session[General.ViewedDetailsId].ToString()] != null)
        if (Cache["flights" + Session["flightsid"].ToString()] != null)
        {
            //DataTable dtSummary = (DataTable)Cache["flights" + Session[General.ViewedDetailsId].ToString()];

            DataTable dtSummary = (DataTable)Cache["flights" + Session["flightsid"].ToString()];
            lblCount.Text = dtSummary.Rows[gvFlightsResults.SelectedIndex]["ResultsCount"].ToString();
        }
        else
        {
            //Response.Redirect("flights-search.aspx");
            Response.Redirect("~/travel-flights/");
        }
    }

    private void GetFlightDetails()
    {
        DataTable dtDetails = getFlightResult_step2();

        PagedDataSource pgitems = new PagedDataSource();
        DataView dv = new DataView(dtDetails);
        pgitems.DataSource = dv;
        pgitems.AllowPaging = true;
        pgitems.PageSize = 10;
        pgitems.CurrentPageIndex = PageNumber;
        if (pgitems.PageCount > 1)
        {
            rptPages.Visible = true;
            divPaging.Visible = true;

            rptPagesBottom.Visible = true;
            divPaging2.Visible = true;

            ArrayList pages = new ArrayList();
            for (int i = 0; i < pgitems.PageCount; i++)
                pages.Add((i + 1).ToString());
            rptPages.DataSource = pages;
            rptPages.DataBind();
            rptPagesBottom.DataSource = pages;
            rptPagesBottom.DataBind();
        }
        else
        {
            //rptPages.Visible = false;
            //divPaging.Visible = false;

            //rptPagesBottom.Visible = false;
            //divPaging2.Visible = false;
        }

        if (pgitems.Count > 0)
        {
            rptDetails.DataSource = pgitems;

            //rptDetails.DataSource = dtDetails;
            rptDetails.DataBind();

            string _strCount = rptDetails.Items.Count.ToString();
            string _strCountAll = dtDetails.Rows.Count.ToString();
            lblCount.Text = "Showing " + _strCount + " of " + _strCountAll + " results";
        }

        rptDetails.Visible = true;
        gvFlightsResults.Visible = false;

        //imgbtnViewSummary.Visible = true;

        //Get Count
        CheckSession();
        //if (Cache["flights" + Session[General.ViewedDetailsId].ToString()] != null)
        //if (Cache["flights" + Session["flightsid"].ToString()] != null)
        //{
        //    //DataTable dtSummary = (DataTable)Cache["flights" + Session[General.ViewedDetailsId].ToString()];

        //    DataTable dtSummary = (DataTable)Cache["flights" + Session["flightsid"].ToString()];
        //    lblCount.Text = dtSummary.Rows[gvFlightsResults.SelectedIndex]["ResultsCount"].ToString();
        //}
        //else
        //{
        //    //Response.Redirect("flights-search.aspx");
        //    Response.Redirect("~/travel-flights/");
        //}
    }

    private void GetFlightDetails(SkyscannerDataInfo _objSkyscannerDataInfo)
    {
        DataTable dtDetails = ToDataTable(_objSkyscannerDataInfo.Itineraries);

        PagedDataSource pgitems = new PagedDataSource();
        DataView dv = new DataView(dtDetails);
        pgitems.DataSource = dv;
        pgitems.AllowPaging = true;
        pgitems.PageSize = 10;
        pgitems.CurrentPageIndex = PageNumber;
        if (pgitems.PageCount > 1)
        {
            rptPages.Visible = true;
            divPaging.Visible = true;

            rptPagesBottom.Visible = true;
            divPaging2.Visible = true;

            ArrayList pages = new ArrayList();
            for (int i = 0; i < pgitems.PageCount; i++)
                pages.Add((i + 1).ToString());
            rptPages.DataSource = pages;
            rptPages.DataBind();
            rptPagesBottom.DataSource = pages;
            rptPagesBottom.DataBind();
        }
        else
        {
            //rptPages.Visible = false;
            //divPaging.Visible = false;

            //rptPagesBottom.Visible = false;
            //divPaging2.Visible = false;

            rptPages.DataSource = null;
            rptPages.DataBind();

            rptPagesBottom.DataSource = null;
            rptPagesBottom.DataBind();
        }

        if (pgitems.Count > 0)
        {
            rptDetails.DataSource = pgitems;

            //rptDetails.DataSource = dtDetails;
            rptDetails.DataBind();

            string _strCount = rptDetails.Items.Count.ToString();
            string _strCountAll = dtDetails.Rows.Count.ToString();
            lblCount.Text = "Showing " + _strCount + " of " + _strCountAll + " results";
        }

        rptDetails.Visible = true;
        gvFlightsResults.Visible = false;

        //imgbtnViewSummary.Visible = true;

        //Get Count
        CheckSession();
        //if (Cache["flights" + Session[General.ViewedDetailsId].ToString()] != null)
        //if (Cache["flights" + Session["flightsid"].ToString()] != null)
        //{
        //    //DataTable dtSummary = (DataTable)Cache["flights" + Session[General.ViewedDetailsId].ToString()];

        //    DataTable dtSummary = (DataTable)Cache["flights" + Session["flightsid"].ToString()];
        //    lblCount.Text = dtSummary.Rows[gvFlightsResults.SelectedIndex]["ResultsCount"].ToString();
        //}
        //else
        //{
        //    //Response.Redirect("flights-search.aspx");
        //    Response.Redirect("~/travel-flights/");
        //}
    }

    protected void rptDetails_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (rptDetails.Items.Count < 1)
        {
            if (e.Item.ItemType == ListItemType.Header)
            {
                HtmlGenericControl noRecordsDiv = (e.Item.FindControl("rptDetailsNoRecords") as HtmlGenericControl);
                if (noRecordsDiv != null)
                {
                    noRecordsDiv.Visible = true;
                }
                HtmlGenericControl hasRecordsDiv = (e.Item.FindControl("rptDetailsHasRecords") as HtmlGenericControl);
                if (hasRecordsDiv != null)
                {
                    hasRecordsDiv.Visible = false;
                }
            }
        }
        else
        {
            HtmlGenericControl noRecordsDiv = ((e.Item.Parent as Repeater).Controls[0].Controls[0].FindControl("rptDetailsNoRecords") as HtmlGenericControl);
            if (noRecordsDiv != null)
            {
                noRecordsDiv.Visible = false;
            }
            HtmlGenericControl hasRecordsDiv = ((e.Item.Parent as Repeater).Controls[0].Controls[0].FindControl("rptDetailsHasRecords") as HtmlGenericControl);
            if (hasRecordsDiv != null)
            {
                hasRecordsDiv.Visible = true;
            }
        }

        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            SkyscannerDataInfo _objSkyscannerDataInfo = (SkyscannerDataInfo)Cache["FlightList"];

            int OutboundNoOfStops = 0;
            int InboundNoOfStops = 0;

            //if (DataBinder.Eval(e.Item.DataItem, "InboundNoOfStops").ToString() != "")
            //    InboundNoOfStops = int.Parse(DataBinder.Eval(e.Item.DataItem, "InboundNoOfStops").ToString());

            //if (DataBinder.Eval(e.Item.DataItem, "OutboundNoOfStops").ToString() != "")
            //    OutboundNoOfStops = int.Parse(DataBinder.Eval(e.Item.DataItem, "OutboundNoOfStops").ToString());

            //Image imgAirLogo = new Image();
            //imgAirLogo = (Image)e.Item.FindControl("imgAirlineLogo");

            //string _airlinecode = DataBinder.Eval(e.Item.DataItem, "AirlineCode").ToString();
            //imgAirLogo.ImageUrl = "http://media.wego.com/images/flights/airlines/80x27/" + _airlinecode + ".gif";


            //set pricing details details
            Currencies _objCurrency = _objSkyscannerDataInfo.Currencies.Find(x => x.Code == _objSkyscannerDataInfo.Query.Currency);
            Itineraries _objItineraries = _objSkyscannerDataInfo.Itineraries.Find(x => x.OutboundLegId == (e.Item.DataItem as DataRowView).Row.ItemArray[0].ToString());
            Agents _objPricingOptionsAgent = _objSkyscannerDataInfo.Agents.Find(x => x.Id == _objItineraries.PricingOptions[0].Agents[0]);

            string fr = locfrom;
            string to = locto;

            string bookingcode = "";
            string provider = _objPricingOptionsAgent.Name;
            string fromlocation = fr;
            string tolocation = to;

            Label lblPrice = new Label();
            lblPrice = (Label)e.Item.FindControl("lblPrice");
            lblPrice.Text = _objCurrency.Symbol + " " + String.Format("{0:0,0.00}", _objItineraries.PricingOptions[0].Price.ToString());

            //set outbound leg details
            string _strOutboundLegId = _objItineraries.OutboundLegId;
            Legs _objOutboundLegs = _objSkyscannerDataInfo.Legs.Find(x => x.Id == _strOutboundLegId);
            Places _objOutboundOriginStation = _objSkyscannerDataInfo.Places.Find(x => x.Id == _objOutboundLegs.OriginStation);
            Places _objOutboundDestinationStation = _objSkyscannerDataInfo.Places.Find(x => x.Id == _objOutboundLegs.DestinationStation);
            Carriers _objOutboundCarriers = _objSkyscannerDataInfo.Carriers.Find(x => x.Id == _objOutboundLegs.Carriers[0]);

            //Outbound Flight Details
            //string[] outboundAirports = DataBinder.Eval(e.Item.DataItem, "OutboundAirports").ToString().Split(',');
            string outboundFlightNos = _objOutboundCarriers.Code;

            Label lblOutboundDepartureDate = new Label();
            lblOutboundDepartureDate = (Label)e.Item.FindControl("lblOutboundDepartureDate");

            Label lblOutboundDepartureFlightNo = new Label();
            lblOutboundDepartureFlightNo = (Label)e.Item.FindControl("lblOutboundDepartureFlightNo");

            Label lblOutboundDepartureTime = new Label();
            lblOutboundDepartureTime = (Label)e.Item.FindControl("lblOutboundDepartureTime");

            Label lblAirportFrom = new Label();
            lblAirportFrom = (Label)e.Item.FindControl("lblAirportFrom");

            Label lblLocationFrom = new Label();
            lblLocationFrom = (Label)e.Item.FindControl("lblLocationFrom");

            Label lblOutboundArrivalTime = new Label();
            lblOutboundArrivalTime = (Label)e.Item.FindControl("lblOutboundArrivalTime");

            Label lblAirportTo = new Label();
            lblAirportTo = (Label)e.Item.FindControl("lblAirportTo");

            Label lblLocationTo = new Label();
            lblLocationTo = (Label)e.Item.FindControl("lblLocationTo");

            Label lblOutboundDuration = new Label();
            lblOutboundDuration = (Label)e.Item.FindControl("lblOutboundDuration");

            PlaceHolder phAirlines = new PlaceHolder();
            phAirlines = (PlaceHolder)e.Item.FindControl("phAirlines");

            lblOutboundDepartureDate.Text = _objOutboundLegs.Departure.ToString("ddd, dd MMMM yyyy");

            DateTime dtOutboundDepartTime;
            string stroutbounddeparture = _objOutboundLegs.Departure.ToString();

            //if (stroutbounddeparture.IndexOf("+") > 0)
            //    dtOutboundDepartTime = Convert.ToDateTime(stroutbounddeparture.Remove(stroutbounddeparture.IndexOf("+", 5)));
            //else
            //    dtOutboundDepartTime = Convert.ToDateTime(stroutbounddeparture.Remove(stroutbounddeparture.IndexOf("-", 5)));

            lblOutboundDepartureTime.Text = _objOutboundLegs.Departure.ToString("ddd, dd MMMM yyyy HH:mm");
            lblOutboundArrivalTime.Text = _objOutboundLegs.Arrival.ToString("ddd, dd MMMM yyyy HH:mm");

            //check flight
            lblOutboundDepartureFlightNo.Text = outboundFlightNos;

            //string airlinecode = DataBinder.Eval(e.Item.DataItem, "AirlineCode").ToString().Trim();
            //string outflightcode = outboundFlightNos[0].Trim().Substring(0, 2);
            //if (outflightcode != airlinecode)
            //{}

            Image imgOutAirlines = new Image();
            imgOutAirlines = (Image)e.Item.FindControl("imgOutboundAirlines");
            imgOutAirlines.ImageUrl = _objOutboundCarriers.ImageUrl;


            lblAirportFrom.Text = _objOutboundOriginStation.Name;
            lblLocationFrom.Text = _objOutboundOriginStation.Code; // DataBinder.Eval(e.Item.DataItem, "LocationFrom").ToString();            
            lblAirportTo.Text = _objOutboundDestinationStation.Name;
            lblLocationTo.Text = _objOutboundDestinationStation.Code; // DataBinder.Eval(e.Item.DataItem, "LocationTo").ToString();            

            double _outtotalminduration = double.Parse(_objOutboundLegs.Duration.ToString());
            double _outhourduration = _outtotalminduration / 60;
            string[] _outgethour = _outhourduration.ToString().Split('.');

            if (_outgethour.Length > 1)
            {
                Double _outminduration = Convert.ToDouble("0." + _outgethour[1].ToString()) * 60;
                Double _outmins = System.Math.Round(_outminduration);
                lblOutboundDuration.Text = _outgethour[0] + "h " + _outmins.ToString() + "m";
            }
            else
                lblOutboundDuration.Text = _outgethour[0] + "h ";

            
            ////get out/inbound connecting details
            //string outboundflightconnecting = "";
            //string inboundflightconnecting = "";

            //DataTable dtWegoConnectingDetails = new DataTable();
            //dtWegoConnectingDetails = myflight.GetFlightDetails(instanceid, DataBinder.Eval(e.Item.DataItem, "ID").ToString(), outbounddate, inbounddate);

            //if (dtWegoConnectingDetails != null && dtWegoConnectingDetails.Rows.Count != 0)
            //{
            //    string outboundconnwego = "";
            //    string inboundconnwego = "";

            //    foreach (DataRow rowdtl in dtWegoConnectingDetails.Rows)
            //    {
            //        if (rowdtl["OutboundflightNumber"] != "")
            //        {
            //            outboundconnwego = outboundconnwego + "|" + rowdtl["OutboundflightNumber"].ToString() + ", " +
            //                rowdtl["OutbounddepartureDateTime"].ToString() + ", " +
            //                rowdtl["OutboundarrivalDateTime"].ToString() + ", " +
            //                rowdtl["OutbounddurationInMin"].ToString() + ", " +
            //                rowdtl["OutboundUTCLocalDepartureTimeVariation"].ToString() + ", " +
            //                rowdtl["OutboundUTCLocalArrivalTimeVariation"].ToString();
            //        }

            //        if (rowdtl["InboundflightNumber"] != "")
            //        {
            //            inboundconnwego = inboundconnwego + "|" + rowdtl["InboundflightNumber"].ToString() + ", " +
            //                rowdtl["InbounddepartureDateTime"].ToString() + ", " +
            //                rowdtl["InboundarrivalDateTime"].ToString() + ", " +
            //                rowdtl["InbounddurationInMin"].ToString() + ", " +
            //                rowdtl["InboundUTCLocalDepartureTimeVariation"].ToString() + ", " +
            //                rowdtl["InboundUTCLocalArrivalTimeVariation"].ToString();
            //        }
            //    }

            //    outboundflightconnecting = outboundconnwego;
            //    inboundflightconnecting = inboundconnwego;
            //}


            ////connecting flights
            //if (OutboundNoOfStops > 0)
            //{
            //    double _outtotalminlayover = double.Parse(DataBinder.Eval(e.Item.DataItem, "OutboundLayOverInMin").ToString());

            //    PlaceHolder phConnecting = new PlaceHolder();
            //    phConnecting = (PlaceHolder)e.Item.FindControl("phConnecting");

            //    phConnecting.Visible = true;
            //    phConnecting.Controls.Clear();

            //    int tblRows = OutboundNoOfStops;
            //    int tblCols = 4;
            //    Table tbl = new Table();
            //    phConnecting.Controls.Add(tbl);


            //    //if (DataBinder.Eval(e.Item.DataItem, "OutboundConnectingDetails").ToString().Length > 0)
            //    if (outboundflightconnecting.Length > 0)
            //    {
            //        //string[] outboundconnecting = DataBinder.Eval(e.Item.DataItem, "OutboundConnectingDetails").ToString().Remove(0, 1).Split('|');
            //        string[] outboundconnecting = outboundflightconnecting.Remove(0, 1).Split('|');


            //        for (int i = 0; i < tblRows; i++)
            //        {
            //            TableRow trlayover = new TableRow();
            //            TableCell tclayover = new TableCell();

            //            Label lblOutboundLayover = new Label();
            //            lblOutboundLayover.Text = "";
            //            lblOutboundLayover.Style.Add("font-weight", "bold");

            //            int outboundairportrecno = 0;

            //            if (i == 0)
            //            {
            //                outboundairportrecno = i + 1;
            //            }
            //            else
            //            {
            //                outboundairportrecno = (i * 2) + 1;
            //            }

            //            string layoverairport = GetAirportLocation(searchid, outboundAirports[outboundairportrecno]);

            //            if (tblRows == 1)
            //            {
            //                double _outhourlayover = _outtotalminlayover / 60;
            //                string[] _outgethourlayover = _outhourlayover.ToString().Split('.');

            //                if (_outgethourlayover.Length > 1)
            //                {
            //                    Double _outminlayover = Convert.ToDouble("0." + _outgethourlayover[1].ToString()) * 60;
            //                    Double _outmins = System.Math.Round(_outminlayover);
            //                    lblOutboundLayover.Text = _outgethourlayover[0] + "h " + _outmins.ToString() + "m Layover in " + layoverairport;
            //                }
            //                else
            //                    lblOutboundLayover.Text = _outgethourlayover[0] + "h Layover in " + layoverairport;
            //            }
            //            else
            //            {
            //                if (outboundconnecting.Length > 1)
            //                {
            //                    DateTime dtArrive;
            //                    DateTime dtDepart;

            //                    string[] outbounddetails = new string[1];
            //                    string[] outbounddetails2 = new string[1];

            //                    outbounddetails = outboundconnecting[i].Split(',');
            //                    //DateTime dtArrivalFormat = DateTime.Parse(outbounddetails[2].Remove(outbounddetails[2].IndexOf("G"), 9));
            //                    DateTime dtArrivalFormat = DateTime.Parse(outbounddetails[2].Remove(outbounddetails[2].IndexOf("S"), 3));
            //                    DateTime dtDepartFormat = CE.Global.General.GetUTCDateTime();

            //                    if (outboundconnecting.Length > (i + 1))
            //                    {
            //                        outbounddetails2 = outboundconnecting[i + 1].Split(',');
            //                        //dtDepartFormat = DateTime.Parse(outbounddetails2[1].Remove(outbounddetails2[1].IndexOf("G"), 9));
            //                        dtDepartFormat = DateTime.Parse(outbounddetails2[1].Remove(outbounddetails2[1].IndexOf("S"), 3));
            //                    }

            //                    int iHour = GetHoursToAdjust(outbounddetails[5]);

            //                    dtArrive = dtArrivalFormat.AddHours(iHour);
            //                    dtDepart = dtDepartFormat.AddHours(iHour);

            //                    TimeSpan ts = dtDepart - dtArrive;

            //                    lblOutboundLayover.Text = ts.Hours.ToString() + "h " + ts.Minutes.ToString() + "m Layover in " + layoverairport;
            //                }
            //            }

            //            HtmlGenericControl _separatorline1 = new HtmlGenericControl("div");
            //            _separatorline1.Attributes.Add("class", "seperator_connecting");

            //            HtmlGenericControl _separatorline2 = new HtmlGenericControl("div");
            //            _separatorline2.Attributes.Add("class", "seperator_connecting");

            //            tclayover.Controls.Add(_separatorline1);
            //            tclayover.Controls.Add(lblOutboundLayover);
            //            tclayover.Controls.Add(_separatorline2);
            //            tclayover.ColumnSpan = 4;
            //            tclayover.CssClass = "table_connecting";
            //            trlayover.Cells.Add(tclayover);


            //            TableRow tr = new TableRow();
            //            for (int j = 0; j < tblCols; j++)
            //            {
            //                TableCell tc = new TableCell();

            //                if (j == 0)
            //                {
            //                    string[] outboundconndetails = new string[1];


            //                    Image imgAirlines = new Image();

            //                    if (outboundconnecting.Length > 1)
            //                    {
            //                        if (outboundconnecting.Length > (i + 1))
            //                        {
            //                            outboundconndetails = outboundconnecting[i + 1].Split(',');
            //                            string flightcode = outboundconndetails[0].Substring(0, 2);

            //                            imgAirlines.ImageUrl = "http://media.wego.com/images/flights/airlines/80x27/" + flightcode + ".gif";
            //                            imgAirlines.BorderStyle = BorderStyle.Solid;
            //                            imgAirlines.BorderWidth = 1;
            //                            imgAirlines.BorderColor = System.Drawing.Color.FromName("#d3d3d3");
            //                        }
            //                    }

            //                    tc.Controls.Add(imgAirlines);
            //                    tc.Width = 84;

            //                }

            //                if (j == 1)
            //                {
            //                    Label lblFlightNo = new Label();
            //                    lblFlightNo.Style.Add("font-weight", "bold");

            //                    string[] outboundconndetails = new string[1];

            //                    if (outboundconnecting.Length > 1)
            //                    {
            //                        if (outboundconnecting.Length > (i + 1))
            //                        {
            //                            outboundconndetails = outboundconnecting[i + 1].Split(',');

            //                            if (outboundconndetails[0].IndexOf("/") > 0)
            //                            {
            //                                lblFlightNo.Text = outboundconndetails[0] + "<br /> *code sharing";
            //                            }
            //                            else
            //                            {
            //                                lblFlightNo.Text = outboundconndetails[0];//outboundFlightNos[i + 1];
            //                            }


            //                        }
            //                    }

            //                    tc.Controls.Add(lblFlightNo);
            //                    tc.HorizontalAlign = HorizontalAlign.Center;
            //                    tc.Width = 108;
            //                }
            //                if (j == 2)
            //                {
            //                    string[] outboundconndetails = new string[1];

            //                    Label lblDepartDate = new Label();

            //                    if (outboundconnecting.Length > 1)
            //                    {
            //                        if (outboundconnecting.Length > (i + 1))
            //                        {
            //                            outboundconndetails = outboundconnecting[i + 1].Split(',');

            //                            int iHour = GetHoursToAdjust(outboundconndetails[4]);

            //                            //DateTime dtDepartFormat = DateTime.Parse(outboundconndetails[1].Remove(outboundconndetails[1].IndexOf("G"), 9));
            //                            DateTime dtDepartFormat = DateTime.Parse(outboundconndetails[1].Remove(outboundconndetails[1].IndexOf("S"), 3));

            //                            lblDepartDate.Text = dtDepartFormat.AddHours(iHour).ToString("ddd, dd MMMM yyyy HH:mm");
            //                        }

            //                    }

            //                    lblDepartDate.Style.Add("font-weight", "bold");

            //                    HtmlGenericControl _nextline = new HtmlGenericControl("div");

            //                    Label lblFromloc = new Label();

            //                    int RecNo = (i + 1) * 2;
            //                    lblFromloc.Text = "Departs From " + GetAirportLocation(searchid, outboundAirports[RecNo]) + " - " + outboundAirports[RecNo];

            //                    tc.Controls.Add(lblDepartDate);
            //                    tc.Controls.Add(_nextline);
            //                    tc.Controls.Add(lblFromloc);
            //                    //tc.Width = 250;
            //                }

            //                if (j == 3)
            //                {
            //                    string[] outboundconndetails = new string[1];
            //                    string[] outboundconndetails2 = new string[1];

            //                    Label lblArrivalDate = new Label();
            //                    lblArrivalDate.Style.Add("font-weight", "bold");

            //                    if (outboundconnecting.Length > 1)
            //                    {
            //                        outboundconndetails = outboundconnecting[i].Split(',');

            //                        //DateTime dtArrivalFormat = DateTime.Parse(outboundconndetails[2].Remove(outboundconndetails[2].IndexOf("G"), 9));
            //                        DateTime dtArrivalFormat = DateTime.Parse(outboundconndetails[2].Remove(outboundconndetails[2].IndexOf("S"), 3));
            //                        int iHour = GetHoursToAdjust(outboundconndetails[5]);

            //                        if (i == 0)
            //                            lblOutboundArrivalTime.Text = dtArrivalFormat.AddHours(iHour).ToString("ddd, dd MMMM yyyy HH:mm");


            //                        if (tblRows > 1)
            //                        {
            //                            if (outboundconnecting.Length > (i + 1))
            //                            {
            //                                outboundconndetails2 = outboundconnecting[i + 1].Split(',');
            //                                iHour = GetHoursToAdjust(outboundconndetails2[5]);

            //                                //DateTime dtArrivalFormat2 = DateTime.Parse(outboundconndetails2[2].Remove(outboundconndetails2[2].IndexOf("G"), 9));
            //                                DateTime dtArrivalFormat2 = DateTime.Parse(outboundconndetails2[2].Remove(outboundconndetails2[2].IndexOf("S"), 3));
            //                                lblArrivalDate.Text = dtArrivalFormat2.AddHours(iHour).ToString("ddd, dd MMMM yyyy HH:mm");
            //                            }
            //                        }

            //                    }

            //                    if (i == (OutboundNoOfStops - 1)) //last flight
            //                    {
            //                        string strarrival = DataBinder.Eval(e.Item.DataItem, "OutboundArrivalTime").ToString();
            //                        DateTime dtArrival;

            //                        if (strarrival.IndexOf("+") > 0)
            //                            dtArrival = Convert.ToDateTime(strarrival.Remove(strarrival.IndexOf("+", 5)));
            //                        else
            //                            dtArrival = Convert.ToDateTime(strarrival.Remove(strarrival.IndexOf("-", 5)));

            //                        lblArrivalDate.Text = dtArrival.ToString("ddd, dd MMMM yyyy HH:mm");
            //                    }

            //                    HtmlGenericControl _nextline = new HtmlGenericControl("div");
            //                    //_nextline.InnerHtml = "<br />";

            //                    Label lblToloc = new Label();

            //                    int RecNo = ((i + 1) * 2) + 1;
            //                    lblToloc.Text = "Arrives At " + GetAirportLocation(searchid, outboundAirports[RecNo]) + " - " + outboundAirports[RecNo];

            //                    tc.Controls.Add(lblArrivalDate);
            //                    tc.Controls.Add(_nextline);
            //                    tc.Controls.Add(lblToloc);
            //                    tc.Style.Add("text-align", "right");
            //                    //tc.Width = 200;
            //                }

            //                tr.Cells.Add(tc);
            //                tr.Height = 40;
            //            }
            //            tbl.Rows.Add(trlayover);
            //            tbl.Rows.Add(tr);
            //            tbl.BorderWidth = 0;
            //            //tbl.GridLines = GridLines.Vertical;
            //            //tbl.Width = 540;
            //        }
            //    }
            //}
            //else
            //{ //Direct Flight

            //    string strarrival = DataBinder.Eval(e.Item.DataItem, "OutboundArrivalTime").ToString();
            //    DateTime dtArrival;

            //    if (strarrival != "")
            //    {
            //        if (strarrival.IndexOf("+") > 0)
            //            dtArrival = Convert.ToDateTime(strarrival.Remove(strarrival.IndexOf("+", 5)));
            //        else
            //            dtArrival = Convert.ToDateTime(strarrival.Remove(strarrival.IndexOf("-", 5)));

            //        lblOutboundArrivalTime.Text = dtArrival.ToString("ddd, dd MMMM yyyy HH:mm");
            //    }

            //    HtmlTableRow trConnecting = new HtmlTableRow();
            //    trConnecting = (HtmlTableRow)e.Item.FindControl("trConnecting");
            //    trConnecting.Visible = false;
            //}

            //Return Flight Details
            Label lblInboundDepartureDate = new Label();
            lblInboundDepartureDate = (Label)e.Item.FindControl("lblInboundDepartureDate");

            Label lblInboundFlightNumber = new Label();
            lblInboundFlightNumber = (Label)e.Item.FindControl("lblInboundFlightNumber");

            Label lblInboundDepartureTime = new Label();
            lblInboundDepartureTime = (Label)e.Item.FindControl("lblInboundDepartureTime");

            Label lblInboundAirportTo = new Label();
            lblInboundAirportTo = (Label)e.Item.FindControl("lblInboundAirportTo");

            Label lblInboundLocationTo = new Label();
            lblInboundLocationTo = (Label)e.Item.FindControl("lblInboundLocationTo");

            Label lblInboundArrivalTime = new Label();
            lblInboundArrivalTime = (Label)e.Item.FindControl("lblInboundArrivalTime");

            Label lblInboundAirportFrom = new Label();
            lblInboundAirportFrom = (Label)e.Item.FindControl("lblInboundAirportFrom");

            Label lblInboundLocationFrom = new Label();
            lblInboundLocationFrom = (Label)e.Item.FindControl("lblInboundLocationFrom");

            Label lblInboundDuration = new Label();
            lblInboundDuration = (Label)e.Item.FindControl("lblInboundDuration");


            if (triptype == "roundTrip")
            {
                //set inbound leg details
                string _strInboundLegId = _objItineraries.InboundLegId;
                Legs _objInboundLegs = _objSkyscannerDataInfo.Legs.Find(x => x.Id == _strInboundLegId);
                Places _objInboundOriginStation = _objSkyscannerDataInfo.Places.Find(x => x.Id == _objInboundLegs.OriginStation);
                Places _objInboundDestinationStation = _objSkyscannerDataInfo.Places.Find(x => x.Id == _objInboundLegs.DestinationStation);
                Carriers _objInboundCarriers = _objSkyscannerDataInfo.Carriers.Find(x => x.Id == _objInboundLegs.Carriers[0]);

                //string[] inboundAirports = DataBinder.Eval(e.Item.DataItem, "InboundAirports").ToString().Split(',');
                string inboundFlightNos = _objInboundCarriers.Code;

                DateTime dtDepartTime;
                string strdeparture = _objInboundLegs.Departure.ToString();

                //if (strdeparture.IndexOf("+") > 0)
                //    dtDepartTime = Convert.ToDateTime(strdeparture.Remove(strdeparture.IndexOf("+", 5)));
                //else
                //    dtDepartTime = Convert.ToDateTime(strdeparture.Remove(strdeparture.IndexOf("-", 5)));

                lblInboundDepartureTime.Text = _objInboundLegs.Departure.ToString("ddd, dd MMMM yyyy HH:mm");

                lblInboundDepartureDate.Text = _objInboundLegs.Departure.ToString("ddd, dd MMMM yyyy");
                lblInboundArrivalTime.Text = _objInboundLegs.Arrival.ToString("ddd, dd MMMM yyyy HH:mm");

                lblInboundFlightNumber.Text = inboundFlightNos;

                //string inflightcode = inboundFlightNos[0].Trim().Substring(0, 2);
                //if (inflightcode != airlinecode)
                //{}

                Image imgInAirlines = new Image();
                imgInAirlines = (Image)e.Item.FindControl("imgInboundAirlines");
                imgInAirlines.ImageUrl = _objInboundCarriers.ImageUrl;


                lblInboundAirportFrom.Text = _objInboundOriginStation.Name;
                lblInboundLocationFrom.Text = _objInboundOriginStation.Code;

                lblInboundAirportTo.Text = _objInboundDestinationStation.Name;
                lblInboundLocationTo.Text = _objInboundDestinationStation.Code;

                double _intotalminduration = double.Parse(_objInboundLegs.Duration.ToString());
                double _inhourduration = _intotalminduration / 60;
                string[] _ingethour = _inhourduration.ToString().Split('.');

                if (_ingethour.Length > 1)
                {
                    Double _inminduration = Convert.ToDouble("0." + _ingethour[1].ToString()) * 60;
                    Double _inmins = System.Math.Round(_inminduration);
                    lblInboundDuration.Text = _ingethour[0] + "h " + _inmins.ToString() + "m";
                }
                else
                    lblInboundDuration.Text = _ingethour[0] + "h ";
            

            //    //connecting flight
            //    if (InboundNoOfStops > 0)
            //    {
            //        double _intotalminlayover = double.Parse(DataBinder.Eval(e.Item.DataItem, "InboundLayOverInMin").ToString());

            //        PlaceHolder phConnecting = new PlaceHolder();
            //        phConnecting = (PlaceHolder)e.Item.FindControl("phConnectingReturn");

            //        phConnecting.Visible = true;
            //        phConnecting.Controls.Clear();

            //        int tblRows = InboundNoOfStops;
            //        int tblCols = 4;
            //        Table tbl = new Table();
            //        phConnecting.Controls.Add(tbl);

            //        //if (DataBinder.Eval(e.Item.DataItem, "InboundConnectingDetails").ToString().Length > 0)
            //        if (inboundflightconnecting.Length > 0)
            //        {
            //            //string[] inboundconnecting = DataBinder.Eval(e.Item.DataItem, "InboundConnectingDetails").ToString().Remove(0, 1).Split('|');
            //            string[] inboundconnecting = inboundflightconnecting.Remove(0, 1).Split('|');

            //            for (int i = 0; i < tblRows; i++)
            //            {
            //                TableRow trlayover = new TableRow();
            //                TableCell tclayover = new TableCell();

            //                Label lblInboundLayover = new Label();
            //                lblInboundLayover.Text = "";
            //                lblInboundLayover.Style.Add("font-weight", "bold");

            //                int inboundairportrecno = 0;

            //                if (i == 0)
            //                {
            //                    inboundairportrecno = i + 1;
            //                }
            //                else
            //                {
            //                    inboundairportrecno = (i * 2) + 1;
            //                }
            //                string layoverairport = GetAirportLocation(searchid, inboundAirports[inboundairportrecno]);

            //                if (tblRows == 1)
            //                {
            //                    double _inhourlayover = _intotalminlayover / 60;
            //                    string[] _ingethourlayover = _inhourlayover.ToString().Split('.');

            //                    if (_ingethourlayover.Length > 1)
            //                    {
            //                        Double _inminlayover = Convert.ToDouble("0." + _ingethourlayover[1].ToString()) * 60;
            //                        Double _inmins = System.Math.Round(_inminlayover);
            //                        lblInboundLayover.Text = _ingethourlayover[0] + "h " + _inmins.ToString() + "m Layover in " + layoverairport;
            //                    }
            //                    else
            //                        lblInboundLayover.Text = _ingethourlayover[0] + "h Layover in " + layoverairport;
            //                }
            //                else
            //                {
            //                    if (inboundconnecting.Length > 1)
            //                    {
            //                        DateTime dtArrive;
            //                        DateTime dtDepart;

            //                        string[] inbounddetails = new string[1];
            //                        string[] inbounddetails2 = new string[1];

            //                        inbounddetails = inboundconnecting[i].Split(',');
            //                        //DateTime dtArrivalFormat = DateTime.Parse(inbounddetails[2].Remove(inbounddetails[2].IndexOf("G"), 9));
            //                        DateTime dtArrivalFormat = DateTime.Parse(inbounddetails[2].Remove(inbounddetails[2].IndexOf("S"), 3));
            //                        DateTime dtDepartFormat = CE.Global.General.GetUTCDateTime();

            //                        if (inboundconnecting.Length > (i + 1))
            //                        {
            //                            inbounddetails2 = inboundconnecting[i + 1].Split(',');
            //                            // dtDepartFormat = DateTime.Parse(inbounddetails2[1].Remove(inbounddetails2[1].IndexOf("G"), 9));
            //                            dtDepartFormat = DateTime.Parse(inbounddetails2[1].Remove(inbounddetails2[1].IndexOf("S"), 3));
            //                        }


            //                        int iHour = GetHoursToAdjust(inbounddetails[5]);

            //                        dtArrive = dtArrivalFormat.AddHours(iHour);
            //                        dtDepart = dtDepartFormat.AddHours(iHour);

            //                        TimeSpan ts = dtDepart - dtArrive;

            //                        lblInboundLayover.Text = ts.Hours.ToString() + "h " + ts.Minutes.ToString() + "m Layover in " + layoverairport;
            //                    }
            //                }
            //                HtmlGenericControl _separatorline1 = new HtmlGenericControl("div");
            //                _separatorline1.Attributes.Add("class", "seperator_connecting");

            //                HtmlGenericControl _separatorline2 = new HtmlGenericControl("div");
            //                _separatorline2.Attributes.Add("class", "seperator_connecting");


            //                tclayover.Controls.Add(lblInboundLayover);
            //                tclayover.ColumnSpan = 4;
            //                tclayover.Controls.Add(_separatorline1);
            //                tclayover.Controls.Add(lblInboundLayover);
            //                tclayover.Controls.Add(_separatorline2);
            //                tclayover.ColumnSpan = 4;
            //                tclayover.CssClass = "table_connecting";
            //                //tclayover.Width = 80;
            //                //tclayover.HorizontalAlign = HorizontalAlign.Center;
            //                //tclayover.BackColor = System.Drawing.Color.Gainsboro;                           
            //                //trlayover.Height = 30;
            //                //trlayover.BorderWidth = 0;
            //                trlayover.Cells.Add(tclayover);

            //                TableRow tr = new TableRow();
            //                for (int j = 0; j < tblCols; j++)
            //                {
            //                    TableCell tc = new TableCell();

            //                    if (j == 0)
            //                    {
            //                        string[] inboundconndetails = new string[1];


            //                        Image imgAirlines = new Image();

            //                        if (inboundconnecting.Length > 1)
            //                        {
            //                            if (inboundconnecting.Length > (i + 1))
            //                            {
            //                                inboundconndetails = inboundconnecting[i + 1].Split(',');
            //                                string flightcode = inboundconndetails[0].Substring(0, 2);

            //                                imgAirlines.ImageUrl = "http://media.wego.com/images/flights/airlines/80x27/" + flightcode + ".gif";
            //                                imgAirlines.BorderStyle = BorderStyle.Solid;
            //                                imgAirlines.BorderWidth = 1;
            //                                imgAirlines.BorderColor = System.Drawing.Color.FromName("#d3d3d3");
            //                            }
            //                        }

            //                        tc.Controls.Add(imgAirlines);
            //                        tc.Width = 84;

            //                    }
            //                    if (j == 1)
            //                    {
            //                        Label lblFlightNo = new Label();
            //                        lblFlightNo.Style.Add("font-weight", "bold");

            //                        string[] inboundconndetails = new string[1];

            //                        if (inboundconnecting.Length > 1)
            //                        {
            //                            if (inboundconnecting.Length > (i + 1))
            //                            {
            //                                inboundconndetails = inboundconnecting[i + 1].Split(',');
            //                                if (inboundconndetails[0].IndexOf("/") > 0)
            //                                {
            //                                    lblFlightNo.Text = inboundconndetails[0] + "<br /> *code sharing";
            //                                }
            //                                else
            //                                {
            //                                    lblFlightNo.Text = inboundconndetails[0];//inboundFlightNos[i + 1];
            //                                }

            //                            }
            //                        }


            //                        tc.Controls.Add(lblFlightNo);
            //                        tc.HorizontalAlign = HorizontalAlign.Center;
            //                        tc.Width = 108;
            //                    }
            //                    if (j == 2)
            //                    {
            //                        string[] inboundconndetails = new string[1];

            //                        Label lblDepartDate = new Label();
            //                        lblDepartDate.Style.Add("font-weight", "bold");

            //                        if (inboundconnecting.Length > 1)
            //                        {
            //                            if (inboundconnecting.Length > (i + 1))
            //                            {
            //                                inboundconndetails = inboundconnecting[i + 1].Split(',');
            //                                int iHour = GetHoursToAdjust(inboundconndetails[4]);

            //                                //DateTime dtDepartFormat = DateTime.Parse(inboundconndetails[1].Remove(inboundconndetails[1].IndexOf("G"), 9));
            //                                DateTime dtDepartFormat = DateTime.Parse(inboundconndetails[1].Remove(inboundconndetails[1].IndexOf("S"), 3));
            //                                lblDepartDate.Text = dtDepartFormat.AddHours(iHour).ToString("ddd, dd MMMM yyyy HH:mm");
            //                            }
            //                        }

            //                        HtmlGenericControl _nextline = new HtmlGenericControl("div");

            //                        Label lblFromloc = new Label();
            //                        int RecNo = (i + 1) * 2;
            //                        lblFromloc.Text = "Departs From " + GetAirportLocation(searchid, inboundAirports[RecNo]) + " - " + inboundAirports[RecNo];

            //                        tc.Controls.Add(lblDepartDate);
            //                        tc.Controls.Add(_nextline);
            //                        tc.Controls.Add(lblFromloc);
            //                        //tc.Width = 250;
            //                    }

            //                    if (j == 3)
            //                    {
            //                        string[] inboundconndetails = new string[1];
            //                        string[] inboundconndetails2 = new string[1];

            //                        Label lblArrivalDate = new Label();
            //                        lblArrivalDate.Style.Add("font-weight", "bold");

            //                        if (inboundconnecting.Length > 1)
            //                        {
            //                            inboundconndetails = inboundconnecting[i].Split(',');
            //                            //DateTime dtArrivalFormat = DateTime.Parse(inboundconndetails[2].Remove(inboundconndetails[2].IndexOf("G"), 9));
            //                            DateTime dtArrivalFormat = DateTime.Parse(inboundconndetails[2].Remove(inboundconndetails[2].IndexOf("S"), 3));
            //                            int iHour = GetHoursToAdjust(inboundconndetails[5]);

            //                            if (i == 0)
            //                                lblInboundArrivalTime.Text = dtArrivalFormat.AddHours(iHour).ToString("ddd, dd MMMM yyyy HH:mm");


            //                            if (tblRows > 1)
            //                            {
            //                                if (inboundconnecting.Length > (i + 1))
            //                                {
            //                                    inboundconndetails2 = inboundconnecting[i + 1].Split(',');
            //                                    //DateTime dtArrivalFormat2 = DateTime.Parse(inboundconndetails2[2].Remove(inboundconndetails2[2].IndexOf("G"), 9));
            //                                    DateTime dtArrivalFormat2 = DateTime.Parse(inboundconndetails2[2].Remove(inboundconndetails2[2].IndexOf("S"), 3));
            //                                    iHour = GetHoursToAdjust(inboundconndetails2[5]);
            //                                    lblArrivalDate.Text = dtArrivalFormat2.AddHours(iHour).ToString("ddd, dd MMMM yyyy HH:mm");
            //                                }
            //                            }

            //                        }


            //                        if (i == (InboundNoOfStops - 1)) //last flight
            //                        {
            //                            DateTime dtArrival;
            //                            string strarrival = DataBinder.Eval(e.Item.DataItem, "InboundArrivalTime").ToString();

            //                            if (strarrival != "")
            //                            {
            //                                if (strarrival.IndexOf("+") > 0)
            //                                    dtArrival = Convert.ToDateTime(strarrival.Remove(strarrival.IndexOf("+", 5)));
            //                                else
            //                                    dtArrival = Convert.ToDateTime(strarrival.Remove(strarrival.IndexOf("-", 5)));

            //                                lblArrivalDate.Text = dtArrival.ToString("ddd, dd MMMM yyyy HH:mm");
            //                            }
            //                        }


            //                        HtmlGenericControl _nextline = new HtmlGenericControl("div");
            //                        //_nextline.InnerHtml = "<br />";

            //                        Label lblToloc = new Label();

            //                        int RecNo = ((i + 1) * 2) + 1;
            //                        lblToloc.Text = "Arrives At " + GetAirportLocation(searchid, inboundAirports[RecNo]) + " - " + inboundAirports[RecNo];

            //                        tc.Controls.Add(lblArrivalDate);
            //                        tc.Controls.Add(_nextline);
            //                        tc.Controls.Add(lblToloc);
            //                        tc.Style.Add("text-align", "right");

            //                    }


            //                    tr.Cells.Add(tc);
            //                    tr.Height = 40;
            //                }
            //                tbl.Rows.Add(trlayover);
            //                tbl.Rows.Add(tr);
            //                tbl.BorderWidth = 0;
            //                //tbl.GridLines = GridLines.Vertical;
            //                //tbl.Width = 540;
            //            }
            //        }
            //    }
            //    else
            //    { //Direct Flight
            //        DateTime dtArrival;
            //        string strarrival = DataBinder.Eval(e.Item.DataItem, "InboundArrivalTime").ToString();

            //        if (strarrival != "")
            //        {
            //            if (strarrival.IndexOf("+") > 0)
            //                dtArrival = Convert.ToDateTime(strarrival.Remove(strarrival.IndexOf("+", 5)));
            //            else
            //                dtArrival = Convert.ToDateTime(strarrival.Remove(strarrival.IndexOf("-", 5)));

            //            lblInboundArrivalTime.Text = dtArrival.ToString("ddd, dd MMMM yyyy HH:mm tt");
            //        }

            //        HtmlTableRow trConnectingReturn = new HtmlTableRow();
            //        trConnectingReturn = (HtmlTableRow)e.Item.FindControl("trConnectingReturn");
            //        trConnectingReturn.Visible = false;
            //    }

            }
            else //oneway only
            {
                HtmlTableRow trReturn = new HtmlTableRow();
                trReturn = (HtmlTableRow)e.Item.FindControl("trReturn");
                trReturn.Visible = false;

                HtmlTableRow trReturnHeader = new HtmlTableRow();
                trReturnHeader = (HtmlTableRow)e.Item.FindControl("trReturnHeader");
                trReturnHeader.Visible = false;

            }

            //FareType
            Label lblFareType = new Label();
            lblFareType = (Label)e.Item.FindControl("lblFareType");
            //lblFareType.Text = DataBinder.Eval(e.Item.DataItem, "FareClassOutbound").ToString();
            lblFareType.Text = "Economy";

            //Provider
            Label lblProvider = new Label();
            lblProvider = (Label)e.Item.FindControl("lblProvider");
            lblProvider.Text = provider;

            //Booking link
            HyperLink hlnkContinue = (HyperLink)e.Item.FindControl("hlnkContinue");
            //hlnkContinue.NavigateUrl = "http://www.wego.com/api/flights/redirect.html?bookingCode=" + bookingcode + "&providerId=" + provider + "&dlfrom=" + fr + "&dlto=" + to + "&instanceId=" + instanceid + "&apiKey=c08b4c9e&aff_aid=aa2db162&ts_code=ae2c7";
            //hlnkContinue.NavigateUrl = getBookingDetails_step1(_objItineraries, _objPricingOptionsAgent.Id);
            hlnkContinue.NavigateUrl = "flights-booking-redirect.aspx?deeplink=" + _objItineraries.BookingDetailsLink.Uri + "&out=" + _objItineraries.OutboundLegId + "&in=" + _objItineraries.InboundLegId + "&agent=" + _objPricingOptionsAgent.Id; 

            ////Other Providers
            ////DataTable dtDetails = (DataTable)Cache["flightsdetails" + Session[General.ViewedDetailsId].ToString()];
            //DataTable dtDetails = (DataTable)Cache["flightsdetails" + Session["flightsid"].ToString()];
            //DataView dv = dtDetails.DefaultView;

            //string strFilters = "ID = '" + DataBinder.Eval(e.Item.DataItem, "ID").ToString() + "' ";
            //dv.RowFilter = strFilters;
            ////string strSortExpress = "totalPricePerPassenger ASC";
            ////dv.Sort = strSortExpress;

            //DataTable dtFiltered = dv.ToTable();

            //if (dtFiltered.Rows.Count > 1)
            //{
            //    HtmlTableRow trOtherProviders = new HtmlTableRow();
            //    trOtherProviders = (HtmlTableRow)e.Item.FindControl("trOtherProviders");
            //    trOtherProviders.Visible = true;

            //    GridView gvProviders = new GridView();
            //    gvProviders = (GridView)e.Item.FindControl("gvProviders");

            //    gvProviders.DataSource = dtFiltered;
            //    gvProviders.DataBind();

            //    HtmlGenericControl divOthers = new HtmlGenericControl("div");
            //    divOthers = (HtmlGenericControl)e.Item.FindControl("divOthers");

            //    HtmlAnchor lnkSeePrices = new HtmlAnchor();
            //    lnkSeePrices = (HtmlAnchor)e.Item.FindControl("lnkSeePrices");
            //    lnkSeePrices.Attributes.Add("onclick", "ShowOtherProviders('" + divOthers.ClientID + "', '" + lnkSeePrices.ClientID + "'); return false;");

            //}

            if (_objItineraries.PricingOptions.Count > 1)
            {
                HiddenField hfLegsID = (HiddenField)e.Item.FindControl("hfLegsID");
                hfLegsID.Value = _objItineraries.OutboundLegId + "&" + _objItineraries.InboundLegId;

                _objItineraries.PricingOptions.RemoveAt(0);
                List<PricingOptions> _objPricingOptions = _objItineraries.PricingOptions.OrderBy(o => o.Price).ToList();

                HtmlTableRow trOtherProviders = new HtmlTableRow();
                trOtherProviders = (HtmlTableRow)e.Item.FindControl("trOtherProviders");
                trOtherProviders.Visible = true;

                GridView gvProviders = new GridView();
                gvProviders = (GridView)e.Item.FindControl("gvProviders");

                gvProviders.DataSource = _objPricingOptions;
                gvProviders.DataBind();

                HtmlGenericControl divOthers = new HtmlGenericControl("div");
                divOthers = (HtmlGenericControl)e.Item.FindControl("divOthers");

                HtmlAnchor lnkSeePrices = new HtmlAnchor();
                lnkSeePrices = (HtmlAnchor)e.Item.FindControl("lnkSeePrices");
                lnkSeePrices.Attributes.Add("onclick", "ShowOtherProviders('" + divOthers.ClientID + "', '" + lnkSeePrices.ClientID + "'); return false;");

            }




        }
    }

    protected void gvProviders_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            SkyscannerDataInfo _objSkyscannerDataInfo = (SkyscannerDataInfo)Cache["FlightList"];
            PricingOptions _objPricingOptions = e.Row.DataItem as PricingOptions;
            Agents _objPricingOptionsAgent = _objSkyscannerDataInfo.Agents.Find(x => x.Id == _objPricingOptions.Agents[0]);

            string _strOutboundLegId = ((e.Row as GridViewRow).Parent.Parent.Parent.FindControl("hfLegsID") as HiddenField).Value.Split('&')[0];
            string _strInboundLegId = ((e.Row as GridViewRow).Parent.Parent.Parent.FindControl("hfLegsID") as HiddenField).Value.Split('&')[1];

            Itineraries _objItineraries = new Itineraries();
            if (_strInboundLegId != "")
                _objItineraries = _objSkyscannerDataInfo.Itineraries.Find(c => (c.OutboundLegId == _strOutboundLegId) && (c.InboundLegId == _strInboundLegId));
            else
                _objItineraries = _objSkyscannerDataInfo.Itineraries.Find(c => (c.OutboundLegId == _strOutboundLegId) && (c.InboundLegId == null));

            //string bookingcode = DataBinder.Eval(e.Row.DataItem, "BookingCode").ToString();
            //string provider = DataBinder.Eval(e.Row.DataItem, "Provider").ToString();
            //string faretype = DataBinder.Eval(e.Row.DataItem, "FareClassOutbound").ToString();

            Image imgProviderLogo = new Image();
            imgProviderLogo = (Image)e.Row.FindControl("imgProviderLogo");
            imgProviderLogo.ImageUrl = _objPricingOptionsAgent.ImageUrl;
            imgProviderLogo.AlternateText = _objPricingOptionsAgent.Name;
            if (_objPricingOptionsAgent.Name == "ebookers")
                imgProviderLogo.ImageUrl = "~/images/flights/ebookers_logo.gif";

            //FareType
            Label lblFareType = new Label();
            lblFareType = (Label)e.Row.FindControl("lblFareType");
            lblFareType.Text = "Economy"; //faretype;


            //FareType
            Label lblPrice = new Label();
            lblPrice = (Label)e.Row.FindControl("lblPrice");
            //lblPrice.Text = DataBinder.Eval(e.Row.DataItem, "totalPricePerPassenger").ToString();
            lblPrice.Text = DataBinder.Eval(e.Row.DataItem, "Price").ToString();

            HyperLink hlnkProvider = (HyperLink)e.Row.FindControl("hlnkProvider");
            //hlnkProvider.NavigateUrl = "http://www.wego.com/api/flights/redirect.html?bookingCode=" + bookingcode + "&providerId=" + provider + "&dlfrom=" + locfrom + "&dlto=" + locto + "&instanceId=" + instanceid + "&apiKey=c08b4c9e&";
            //hlnkProvider.NavigateUrl = "http://www.wego.com/api/flights/redirect.html?bookingCode=" + bookingcode + "&providerId="
            //    + provider + "&dlfrom=" + locfrom + "&dlto=" + locto + "&instanceId=" + instanceid + "&apiKey=c08b4c9e&aff_aid=aa2db162&ts_code=ae2c7";
            //hlnkProvider.NavigateUrl = getBookingDetails_step1(_objItineraries, _objPricingOptionsAgent.Id);
            hlnkProvider.NavigateUrl = "flights-booking-redirect.aspx?deeplink=" + _objItineraries.BookingDetailsLink.Uri + "&out=" + _objItineraries.OutboundLegId + "&in=" + _objItineraries.InboundLegId + "&agent=" + _objPricingOptionsAgent.Id; 

        }
    }

    private DataTable SortFlights(Int64 SearchId, string Airlines)
    {
        DataTable dtNew = new DataTable();

        DataTable dtDistinct = wegodb.GetWegoFlightsInfoDistinctFlights(SearchId, Airlines);
        DataTable dtDetails = new DataTable();

        dtDetails = wegodb.GetWegoFlightsInfoDetails(SearchId, Airlines);
        //Cache["flightsdetails" + Session[General.ViewedDetailsId].ToString()] = dtDetails;
        Cache["flightsdetails" + Session["flightsid"].ToString()] = dtDetails;


        DataView dv = dtDetails.DefaultView;

        foreach (DataRow dr in dtDistinct.Rows)
        {
            string strFilters = "ID = '" + dr["id"].ToString() + "' and totalPricePerPassenger = '" + Convert.ToDecimal(dr["totalPricePerPassenger"].ToString()) + "' ";
            dv.RowFilter = strFilters;

            string strSortExpress = "totalPricePerPassenger ASC";
            dv.Sort = strSortExpress;

            DataTable cloneDataTable = dv.ToTable().Clone();
            cloneDataTable.ImportRow(dv.ToTable().Rows[0]);

            dtNew.Merge(cloneDataTable);
            dtNew.AcceptChanges();

        }

        return dtNew;
    }

    private int GetHoursToAdjust(string utcvalue)
    {
        string plusminus = utcvalue.Substring(1, 1);
        int iHour = 0;
        iHour = (int.Parse(utcvalue.Substring(1, 3)) - 8);

        if (iHour.ToString().Length > 1)
        {
            if (iHour.ToString().Substring(0, 1) != "-")
            {
                iHour = int.Parse(plusminus + iHour);
            }
        }
        else
        {
            iHour = int.Parse(plusminus + iHour);
        }

        return iHour;
    }

    private string GetAirportLocation(Int64 SearchId, string LocationCode)
    {
        string LocationName = "";

        //DataTable dtAirLoc = new DataTable();
        //dtAirLoc = (DataTable)ViewState["airlocation"];
        //DataView dvLoc = dtAirLoc.DefaultView;

        //string strFilters = "LocationCode = '" + LocationCode + "' ";
        //dvLoc.RowFilter = strFilters;

        ////LocationName = dvLoc.Table.Rows[0]["LocationName"].ToString();
        //if (dvLoc.Count > 0)
        //{
        //    LocationName = dvLoc[0][3].ToString();
        //}
        ////rptDetails.DataSource = dv;


        LocationName = wegodb.GetAirportLocation(SearchId, LocationCode);

        return LocationName;
    }

    private Int64 LogUserViewedHistory()
    {
        UserViewHistoryDB _userviewdb = new UserViewHistoryDB();
        return _userviewdb.LogViewedHistory("FL", Request, "Travel Flights Results Page.");
    }

    private void CheckSession()
    {
        //if (Session[General.ViewedDetailsId] == null || Session[General.ViewedDetailsId].ToString() == "")
        //{
        //    Response.Redirect("flights-search.aspx");
        //}

        if (Session["flightsid"] == null || Session["flightsid"].ToString() == "")
        {
            //Response.Redirect("flights-search.aspx");
            Response.Redirect("~/travel-flights/");
        }

    }

    protected void gvTAResultsInsurer_RowDatabound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[2].Text = String.Format("${0:f}", e.Row.Cells[2].Text);

            if (e.Row.Cells[2].Text == "0.01")
            {
                e.Row.Cells[2].Text = "";
                Image imgCompanyLogo = (Image)e.Row.FindControl("imgCompanyLogo");
                imgCompanyLogo.Visible = false;
            }
            else
            {
                Image imgCompanyLogo = (Image)e.Row.FindControl("imgCompanyLogo");
                string providercompanyid = DataBinder.Eval(e.Row.DataItem, "providercompanyid").ToString();
                string imageurl = "~/images/public/logo/";

                if (providercompanyid == "23")
                {
                    imageurl += "hsbc_xs.png";
                }
                else if (providercompanyid == "24")
                {
                    imageurl += "rsa_xs.png";
                }
                else if (providercompanyid == "29")
                {
                    imageurl += "liberty_xs.png";
                }
                else if (providercompanyid == "30")
                {
                    imageurl += "etiqa_xs.png";
                }
                else if (providercompanyid == "31")
                {
                    imageurl += "chartis_xs.png";
                }
                else if (providercompanyid == "34")
                {
                    imageurl += "chinataiping_xs.png";
                }
                else if (providercompanyid == "35")
                {
                    imageurl += "eq_xs.png";
                }
                else if (providercompanyid == "36")
                {
                    imageurl += "ace_xs.png";
                }
                else if (providercompanyid == "37")
                {
                    imageurl += "1cover_xs.png";
                }
                else if (providercompanyid == "38")
                {
                    imageurl += "directasia_xs.png";
                }


                imgCompanyLogo.ImageUrl = imageurl;
            }

            if (e.Row.RowIndex == 0)
                e.Row.CssClass = "packone tr";
            else if (e.Row.RowIndex == 1)
                e.Row.CssClass = "packtwo tr";
            else if (e.Row.RowIndex == 2)
                e.Row.CssClass = "packthree tr";
            else if (e.Row.RowIndex == 3)
                e.Row.CssClass = "packfour tr";
            else if (e.Row.RowIndex == 4)
                e.Row.CssClass = "packfive tr";
            else if (e.Row.RowIndex == 5)
                e.Row.CssClass = "packsix tr";
            else if (e.Row.RowIndex == 6)
                e.Row.CssClass = "packseven tr";
            else if (e.Row.RowIndex == 7)
                e.Row.CssClass = "packeight tr";


            ImageButton imgbtnCompare = new ImageButton();
            imgbtnCompare = (ImageButton)e.Row.FindControl("imgbtnCompare");

            //imgbtnCompare.OnClientClick = "javascript:void(0);ShowPopup();return false;";
            //e.Row.Attributes.Add("onmouseover", "javascript:orgBgColor = this.className; this.className = 'gridover';");
            //e.Row.Attributes.Add("onmouseout", "javascript:this.className = orgBgColor;");

        }


        //if (gvTAResultsInsurer.Rows.Count > 0)
        //{
        //    GridViewRow gvRow;

        //    if ((gvTAResultsInsurer.Rows.Count > 0) && (e.Row.RowIndex == -1))
        //    {
        //        int GrdRows = gvTAResultsInsurer.Rows.Count - 1;
        //        gvRow = gvTAResultsInsurer.Rows[GrdRows];
        //    }
        //    else
        //    {
        //        gvRow = gvTAResultsInsurer.Rows[e.Row.RowIndex - 1];
        //    }

        //    if (gvRow.Cells[2].Text == "")
        //    {
        //        gvRow.Cells[1].ColumnSpan = 2;
        //        gvRow.Cells[1].Style.Add("text-align", "left");
        //        gvRow.Cells[1].Style.Add("font-weight", "bold");
        //        gvRow.Cells[2].Visible = false;
        //    }

        //}


    }

    protected void gvTAResultsInsurer_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Compare"))
        {
            //Sakthi on 07 Mar 2011 -- start
            //TAApplicantSearchDB _taapplicantsearchdb = new TAApplicantSearchDB();
            //Int64 TAAppSeaId = 0;
            //string Status = "0";
            //if (Session[General.TAId] == null)
            //{
            //    TAAppSeaId = 0;
            //}
            //else
            //{
            //    TAAppSeaId = Convert.ToInt64(Session[General.TAId].ToString());
            //}
            //Status = "2";
            //Int64 _result = _taapplicantsearchdb.UpdateStatus(TAAppSeaId, Status);
            //Sakthi on 07 Mar 2011 -- End

            //Response.Redirect("~/travel_insurance/TAresultsquotesOne.aspx");
            //Response.Redirect("../travel_insurance/travel_quote.aspx");

            //mpeUserInfo.Show();

            //if (Session[General.TAId] != null)
            //{
            //    Cache.Remove("TAResultsQuotes" + Session[General.TAId].ToString());
            //}

            Int64 countryid = 0;
            Int64 areaid = 0;
            string coveragelevel = "S";
            Int32 duration = 0;
            DateTime startdate = new DateTime(1900, 1, 1);
            DateTime enddate = new DateTime(1900, 1, 1);
            Int32 childage = 0;
            Int32 adultage1 = 0;
            Int32 adultage2 = 0;
            Int32 adultage3 = 0;
            Int32 adultage4 = 0;

            Int32 noofadults = 0;
            DateTime dobadult1 = CE.Global.General.GetUTCDateTime();
            DateTime dobadult2 = CE.Global.General.GetUTCDateTime();
            DateTime dobadult3 = CE.Global.General.GetUTCDateTime();
            DateTime dobadult4 = CE.Global.General.GetUTCDateTime();
            Int32 noofchilds = 0;
            DateTime dobchild1 = CE.Global.General.GetUTCDateTime();
            DateTime dobchild2 = CE.Global.General.GetUTCDateTime();
            DateTime dobchild3 = CE.Global.General.GetUTCDateTime();
            DateTime dobchild4 = CE.Global.General.GetUTCDateTime();
            DateTime dobchild5 = CE.Global.General.GetUTCDateTime();
            DateTime dobchild6 = CE.Global.General.GetUTCDateTime();


            DateTime dtout = Convert.ToDateTime(outbounddate);
            DateTime dtin = Convert.ToDateTime(inbounddate);

            //removed popup
            //adultage1 = ComputeAge(userBirthday.GetDate());
            //dobadult1 = userBirthday.GetDate();

            adultage1 = 25; //default
            dobadult1 = CE.Global.General.GetUTCDateTime().AddYears(-25);//default

            noofadults = 1;
            noofchilds = 0;
            coveragelevel = "S";

            //Scenario 1
            countryid = Convert.ToInt64(incountryid.Value.Trim());

            duration = ComputeDuration(dtout, dtin);
            startdate = dtout;
            enddate = dtin;

            string[] customerage = { adultage1.ToString(), adultage2.ToString(), adultage3.ToString(), adultage4.ToString() };
            Session[General.TACustomerAge] = customerage;

            TAApplicantSearch _taapplicantsearch = new TAApplicantSearch();
            TAApplicantSearchDB _taapplicantsearchdb = new TAApplicantSearchDB();

            if (Session[General.TAId] == null)
            {
                _taapplicantsearch.TAAppSeaId = 0;
            }
            else
            {
                _taapplicantsearch.TAAppSeaId = Convert.ToInt64(Session[General.TAId].ToString());
            }

            if (Session[General.UserId] == null)
            {
                _taapplicantsearch.RefCEUserId = 0;
                _taapplicantsearch.Name = txtUserName.Text.ToUpper();
                _taapplicantsearch.EmailAddress = txtUserEmail.Text.Trim();
                _taapplicantsearch.MobileNum = txtMobileNo.GetPhoneNo();
            }
            else
            {
                _taapplicantsearch.RefCEUserId = Convert.ToInt64(Session[General.UserId].ToString());
                _taapplicantsearch.Name = Session[General.UserName].ToString();
                _taapplicantsearch.EmailAddress = Session[General.UserEmail].ToString();
                _taapplicantsearch.MobileNum = Session[General.UserPhoneNo].ToString();
            }

            _taapplicantsearch.PlanType = "IND";
            _taapplicantsearch.TripType = "S";
            _taapplicantsearch.CountryID = countryid;
            _taapplicantsearch.AreaID = areaid;
            _taapplicantsearch.CoverageLevel = coveragelevel;
            _taapplicantsearch.Duration = duration;
            _taapplicantsearch.StartDate = startdate;
            _taapplicantsearch.EndDate = enddate;
            _taapplicantsearch.ChildAge = childage;
            _taapplicantsearch.AdultAge = adultage1;
            _taapplicantsearch.NoOfTravellers = noofadults + noofchilds;
            _taapplicantsearch.TotalPremium = 0;

            _taapplicantsearch.NoofAdults = noofadults;
            _taapplicantsearch.DOBAdult1 = dobadult1;
            _taapplicantsearch.DOBAdult2 = dobadult2;
            _taapplicantsearch.DOBAdult3 = dobadult3;
            _taapplicantsearch.DOBAdult4 = dobadult4;
            _taapplicantsearch.NoofChilds = noofchilds;
            _taapplicantsearch.DOBChild1 = dobchild1;
            _taapplicantsearch.DOBChild2 = dobchild2;
            _taapplicantsearch.DOBChild3 = dobchild3;
            _taapplicantsearch.DOBChild4 = dobchild4;
            _taapplicantsearch.DOBChild5 = dobchild5;
            _taapplicantsearch.DOBChild6 = dobchild6;

            _taapplicantsearch.ViewedDetailId = Convert.ToInt64(Session[General.ViewedDetailsId].ToString());

            _taapplicantsearch.Info1 = "0";
            Int64 _result = _taapplicantsearchdb.Insert(_taapplicantsearch);

            if (_result > 0)
            {
                Session["TripType"] = "S";
                Session[General.TAId] = _result.ToString();

                if (Session[General.UserId] == null)
                {
                    Session[General.TAPersonnelId] = _taapplicantsearch.RefCEUserId.ToString();
                    Session[General.TAUserName] = txtFullName.Text.ToUpper();
                    Session[General.TAPhoneNo] = txtMobileNo.GetPhoneNo().ToString();
                    Session[General.TAEmail] = txtUserEmail.Text.Trim();
                }

                Int64 TAAppSeaId = Convert.ToInt64(Session[General.TAId].ToString());
                string Status = "2";
                Int64 _updateresult = _taapplicantsearchdb.UpdateStatus(TAAppSeaId, Status);
                if (_updateresult > 0)
                {
                    //Response.Redirect("../travel-insurance/taresultsquotesone.aspx");
                    //Response.Redirect("../travel-insurance/results.aspx");
                    Response.Redirect("../travel-insurance/results-details.aspx");
                }
            }

            LogUserViewedHistory();
        }
    }

    private void ResultsQuotesDataBind()
    {
        if (Session[General.TAId] == null)
        {
            //Response.Redirect("flights-search.aspx");
            Response.Redirect("~/travel-flights/");
        }

        GetTempResultTable();

    }

    private void GetTempResultTable()
    {
        string CoverType = "";
        Int32 Duration = 0;
        string CoverageLevel = "S";
        string Trip = "";
        Int64 AreaId = 0;
        Int64 CountryId = 0;
        Int32 AdultAge = 0;
        Int32 ChildAge = 0;
        Int64 TAId = 0;
        Int32 NoOfAdults = 0;

        TAApplicantSearchDB _taapplicantsearchdb = new TAApplicantSearchDB();
        TAApplicantSearch _taapplicantsearch = new TAApplicantSearch();

        if (Session[General.TAId] != null)
            TAId = Convert.ToInt64(Session[General.TAId]);
        else
        {
            //Response.Redirect("flights-search.aspx");
            Response.Redirect("~/travel-flights/");
        }

        _taapplicantsearch = _taapplicantsearchdb.GetTAApplicantSearchItem(TAId);

        if (_taapplicantsearch != null)
        {
            CoverType = _taapplicantsearch.PlanType;
            Session["PlanType"] = _taapplicantsearch.PlanType;
            Duration = _taapplicantsearch.Duration;
            AreaId = _taapplicantsearch.AreaID;
            CountryId = _taapplicantsearch.CountryID;
            AdultAge = _taapplicantsearch.AdultAge;
            ChildAge = _taapplicantsearch.ChildAge;
            CoverageLevel = _taapplicantsearch.CoverageLevel;
            Trip = _taapplicantsearch.TripType;
            NoOfAdults = _taapplicantsearch.NoofAdults;

            incountryid.Value = CountryId.ToString();

            //Left label
            lblTrip.Text = GetTriptype(Trip);
            lblPolicyType.Text = GetCovertype(CoverType);
            lblNoOfTraveller.Text = NoOfAdults.ToString();

            MyDatabase _db = new MyDatabase();
            DataTable _dtResult = new DataTable();

            TAQuoteResultDB _taquoteresultdb = new TAQuoteResultDB();


            if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) ==
                Convert.ToInt32(CE.Global.CEUserType.Provider) && Session[CE.Global.General.ProviderCompanyId] != null)
            {
                _dtResult = _taquoteresultdb.GetTAQuoteResultDisplayByProvider(GetCovertype(CoverType), Duration.ToString(), AreaId, CountryId, AdultAge, ChildAge, CoverageLevel, Convert.ToInt64(Session[CE.Global.General.ProviderCompanyId].ToString()), NoOfAdults, 0, TAId);
            }
            else
            {
                //_dtResult = _taquoteresultdb.GetTAQuoteResultDisplay(GetCovertype(CoverType), Duration.ToString(), AreaId, CountryId, AdultAge, ChildAge, CoverageLevel, Trip, NoOfAdults);
                _dtResult = _taquoteresultdb.GetTAQuoteResultDisplay(GetCovertype(CoverType), Duration.ToString(), AreaId, CountryId, AdultAge, ChildAge, CoverageLevel, Trip, NoOfAdults, 0, TAId);
            }

            //DataRow[] rows = datatable.Select('TOP 5');

            DataView dv = new DataView(_dtResult);
            //            dv.Table.AsEnumerable().Take(5); 
            dv.Sort = "AnnualPremium ASC";

            Cache["TAResultsQuotes" + Session[General.TAId].ToString()] = dv.ToTable();

            string sQueryString = "";

            if (dv.Count > 0)
            {
                for (int i = 0; i < dv.ToTable().Rows.Count; i++)
                {
                    if (i == 7)
                    {
                        break;
                    }

                    string skey = dv.ToTable().Rows[i]["TAInsID"].ToString();
                    sQueryString += skey + ",";
                }


                Session["TASelected"] = sQueryString;
            }

            //gvTAResultsInsurer.DataSource = GetTopTravel(dv, 5);
            gvTAResultsInsurer.DataSource = GetTopDistinct(dv);
            gvTAResultsInsurer.DataBind();

            dlTAResultsInsurer.DataSource = GetTopDistinct(dv).AsEnumerable().Take(4).CopyToDataTable();
            dlTAResultsInsurer.DataBind();

            if (dv.Count == 0)
            {
                divTI.Visible = false;
            }
        }
        else
        {
            //Response.Redirect("flights-search.aspx");
            Response.Redirect("~/travel-flights/");
        }

    }

    private DataView GetTopTravel(DataView dv, Int32 n)
    {
        DataTable dt = dv.Table.Clone();

        for (int i = 0; i <= n - 1; i++)
        {
            if (i >= dv.Count)
            {
                break;
            }
            dt.ImportRow(dv[i].Row);
        }
        return new DataView(dt, dv.RowFilter, dv.Sort, dv.RowStateFilter);


    }

    private DataTable GetTopDistinct(DataView dv)
    {
        DataTable newdt = new DataTable();
        DataTable dt = dv.ToTable();

        string[] providers = new string[8]; //8 providers for now
        newdt = dt.Clone();

        int i = 0;
        foreach (DataRow row in dt.Rows)
        {
            if (i == 0)
            {
                providers[i] = row["ProviderCompanyId"].ToString();

                //newdt.ImportRow(row);
                newdt.Rows.Add(row.ItemArray);

            }
            else
            {
                bool isExisting = false;

                foreach (string prov in providers)
                {
                    if (row["ProviderCompanyId"].ToString() == prov)
                    {
                        isExisting = true;
                    }
                }

                if (!isExisting)
                {
                    if (newdt.Rows.Count < 8) // providers for now
                    {
                        int iprov = 0;
                        foreach (string prov in providers)
                        {
                            if (prov == null)
                            {
                                providers[iprov] = row["ProviderCompanyId"].ToString();

                                break;
                            }

                            iprov++;
                        }

                        newdt.Rows.Add(row.ItemArray);
                    }
                    else
                    {
                        break;
                    }

                }

            }
            i++;

            newdt.AcceptChanges();
        }
        return newdt;

    }

    private string GetCovertype(string covertype)
    {
        string coverparam = "";
        if (covertype == "IND")
            coverparam = "Individual";
        else if (covertype == "INS")
            coverparam = "IndividualSpouse";
        else if (covertype == "FML")
            coverparam = "Family";
        else if (covertype == "INC")
            coverparam = "IndividualChild";

        return coverparam;
    }

    private string GetTriptype(string trip)
    {
        string triptype = "";
        if (trip == "S")
            triptype = "Single Trip";
        else
            triptype = "Annual Multi-Trip";


        return triptype;
    }

    protected void btnBack_Click(object sender, EventArgs e)
    {
        //Cache.Remove("flights" + Session[General.ViewedDetailsId].ToString());
        //if (Cache["flightsdetails" + Session[General.ViewedDetailsId].ToString()] != null)
        //    Cache.Remove("flightsdetails" + Session[General.ViewedDetailsId].ToString());

        Cache.Remove("flights" + Session["flightsid"].ToString());

        if (Cache["flightsdetails" + Session["flightsid"].ToString()] != null)
            Cache.Remove("flightsdetails" + Session["flightsid"].ToString());

        //Response.Redirect("flights-search.aspx");
        Response.Redirect("~/travel-flights/");
    }

    protected void imgbtnRerun_Click(object sender, ImageClickEventArgs e)
    {
        //Response.Redirect("../travel-insurance/travel-quote.aspx");
        Response.Redirect("~/travel-insurance/");
    }

    protected void lnkbtnChange_Click(object sender, EventArgs e)
    {
        //Cache.Remove("flights" + Session[General.ViewedDetailsId].ToString());
        //if (Cache["flightsdetails" + Session[General.ViewedDetailsId].ToString()] != null)
        //    Cache.Remove("flightsdetails" + Session[General.ViewedDetailsId].ToString());

        Cache.Remove("flights" + Session["flightsid"].ToString());

        if (Cache["flightsdetails" + Session["flightsid"].ToString()] != null)
            Cache.Remove("flightsdetails" + Session["flightsid"].ToString());


        //Response.Redirect("flights-search.aspx");
        Response.Redirect("~/travel-flights/");
    }

    protected void imgbtnViewSummary_Click(object sender, ImageClickEventArgs e)
    {
        imgbtnViewSummary.Visible = false;
        rptDetails.Visible = false;
        rptPages.Visible = false;
        rptPagesBottom.Visible = false;
        divPaging.Visible = false;
        divPaging2.Visible = false;

        ViewState["PageNumber"] = null;

        rptPages.DataSource = null;
        rptPages.DataBind();

        rptPagesBottom.DataSource = null;
        rptPagesBottom.DataBind();

        //if (Cache["flightsdetails" + Session[General.ViewedDetailsId].ToString()] != null)
        //    Cache.Remove("flightsdetails" + Session[General.ViewedDetailsId].ToString());

        if (Cache["flightsdetails" + Session["flightsid"].ToString()] != null)
            Cache.Remove("flightsdetails" + Session["flightsid"].ToString());

        lblCount.Text = lblCountAll.Text;
        gvFlightsResults.Visible = true;
    }

    private void ChangeValidationEffectServerSide(string strValidationGroup)
    {
        //Name
        if (rfvFullName.Enabled && rfvFullName.ValidationGroup == strValidationGroup)
        {
            rfvFullName.Validate();
            if (rfvFullName.IsValid == false)
            {
                txtFullName.ControlStyle.CssClass = "validationError";
            }
            else
            {
                txtFullName.ControlStyle.CssClass = "";
            }
        }
        else
        {
            txtFullName.ControlStyle.CssClass = "";
        }

        //Email Address
        if (rfvEmailAddress.Enabled && rfvEmailAddress.ValidationGroup == strValidationGroup)
        {
            rfvEmailAddress.Validate();
            if (rfvEmailAddress.IsValid == false)
            {
                txtEmailAddress.ControlStyle.CssClass = "validationError";
            }
            else
            {
                txtEmailAddress.ControlStyle.CssClass = "";
            }
        }
        else
        {
            txtEmailAddress.ControlStyle.CssClass = "";
        }

        if (revEmailAddress.Enabled && revEmailAddress.ValidationGroup == strValidationGroup)
        {
            if (rfvEmailAddress.IsValid)
            {
                revEmailAddress.Validate();
                if (revEmailAddress.IsValid == false)
                {
                    txtEmailAddress.ControlStyle.CssClass = "validationError";
                }
                else
                {
                    txtEmailAddress.ControlStyle.CssClass = "";
                }
            }
        }
        else
        {
            txtEmailAddress.ControlStyle.CssClass = "";
        }
        //txtMobileNo.ChangeValidationEffectServerSide(strValidationGroup);

        //Reminder Month
        if (rfvMonth.Enabled && rfvMonth.ValidationGroup == strValidationGroup)
        {
            rfvMonth.Validate();
            if (rfvMonth.IsValid == false)
            {
                ddlMonth.ControlStyle.CssClass = "validationError";
            }
            else
            {
                ddlMonth.ControlStyle.CssClass = "";
            }
        }
        else
        {
            ddlMonth.ControlStyle.CssClass = "";
        }


    }

    protected void btnSetReminder_Click(object sender, EventArgs e)
    {
        Page.Validate("reminder");
        ChangeValidationEffectServerSide("reminder");
        if (Page.IsValid)
        {
            UserSIRTravel _usersir = new UserSIRTravel();
            UserSIRTravelDB _usersirdb = new UserSIRTravelDB();
            _usersir = _usersirdb.GetSIRTravel(txtEmailAddress.Text.Trim(), "99999999");
            if (_usersir == null)
            {
                _usersir = new UserSIRTravel();
                _usersir.SIRTravelID = 0;
                _usersir.FullName = txtFullName.Text;
                _usersir.Email = txtEmailAddress.Text;
                _usersir.MobileNumber = "99999999";// txtMobileNo.GetPhoneNo();
                _usersir.ReminderMonth = Convert.ToInt16(ddlMonth.Text);
                _usersir.Status = true;

                _usersir.SIRTravelID = _usersirdb.Insert(_usersir);
                if (_usersir.SIRTravelID > 0)
                {
                    string _emailTo = CE.Configuration.MyConfigurationManager.GetAppSettingValue("SIRMessageReceiver");
                    string _emailBody = "<br/><table><tr><td>Name</td><td>:</td><td>" + txtFullName.Text + "</td></tr>";
                    _emailBody += "<tr><td>Email</td><td>:</td><td>" + txtEmailAddress.Text + "</td></tr>";
                    // _emailBody += "<tr><td>Mobile</td><td>:</td><td>" + txtMobileNo.GetPhoneNo() + "</td></tr>";
                    _emailBody += "<tr><td>Reminder Month</td><td>:</td><td>" + ddlMonth.SelectedItem.Text + "</td></tr></table><br/><br/>Thank you.";

                    CE.Mail.MyMailManager.SendCRMMessage(_emailTo, "Travel Insurance Reminder (" + txtFullName.Text + ")", _emailBody);
                }
                else
                {
                    lblSetInsMessage.Text = "Transaction failed. Please try again later.";
                }
            }
            else
            {
                _usersir.FullName = txtFullName.Text;
                _usersir.ReminderMonth = Convert.ToInt16(ddlMonth.Text);
                _usersir.SIRTravelID = _usersirdb.Insert(_usersir);
            }

            if (_usersir != null && _usersir.SIRTravelID > 0)
            {
                lblSetInsMessage.Text = "Thank you for your request. We will send reminder to your email.";
                txtFullName.ReadOnly = true;
                txtEmailAddress.ReadOnly = true;
                //txtMobileNo.IsEnabled = false;
                ddlMonth.Enabled = false;
                btnSetReminder.Enabled = false;
                btnSetReminder.Visible = false;
            }
            else
            {
                lblSetInsMessage.Text = "Transaction failed. Please try again later.";
            }
        }
    }

    protected void btnClose_Click(object sender, EventArgs e)
    {
        mpeTravelReminder.Hide();
    }

    protected void btnUserClose_Click(object sender, EventArgs e)
    {
        mpeUserInfo.Hide();
    }

    protected void imgbtnUserInfo_Click(object sender, ImageClickEventArgs e)
    {
        Page.Validate("userinfo");
        ChangeValidationEffectServerSideUserInfo("userinfo");
        if (Page.IsValid)
        {
            //if (Session[General.TAId] != null)
            //{
            //    Cache.Remove("TAResultsQuotes" + Session[General.TAId].ToString());
            //}

            Int64 countryid = 0;
            Int64 areaid = 0;
            string coveragelevel = "S";
            Int32 duration = 0;
            DateTime startdate = new DateTime(1900, 1, 1);
            DateTime enddate = new DateTime(1900, 1, 1);
            Int32 childage = 0;
            Int32 adultage1 = 0;
            Int32 adultage2 = 0;
            Int32 adultage3 = 0;
            Int32 adultage4 = 0;

            Int32 noofadults = 0;
            DateTime dobadult1 = CE.Global.General.GetUTCDateTime();
            DateTime dobadult2 = CE.Global.General.GetUTCDateTime();
            DateTime dobadult3 = CE.Global.General.GetUTCDateTime();
            DateTime dobadult4 = CE.Global.General.GetUTCDateTime();
            Int32 noofchilds = 0;
            DateTime dobchild1 = CE.Global.General.GetUTCDateTime();
            DateTime dobchild2 = CE.Global.General.GetUTCDateTime();
            DateTime dobchild3 = CE.Global.General.GetUTCDateTime();
            DateTime dobchild4 = CE.Global.General.GetUTCDateTime();
            DateTime dobchild5 = CE.Global.General.GetUTCDateTime();
            DateTime dobchild6 = CE.Global.General.GetUTCDateTime();


            DateTime dtout = Convert.ToDateTime(outbounddate);
            DateTime dtin = Convert.ToDateTime(inbounddate);


            adultage1 = ComputeAge(userBirthday.GetDate());
            dobadult1 = userBirthday.GetDate();
            noofadults = 1;
            noofchilds = 0;
            coveragelevel = "S";

            //Scenario 1
            countryid = Convert.ToInt64(incountryid.Value.Trim());

            duration = ComputeDuration(dtout, dtin);
            startdate = dtout;
            enddate = dtin;

            string[] customerage = { adultage1.ToString(), adultage2.ToString(), adultage3.ToString(), adultage4.ToString() };
            Session[General.TACustomerAge] = customerage;

            TAApplicantSearch _taapplicantsearch = new TAApplicantSearch();
            TAApplicantSearchDB _taapplicantsearchdb = new TAApplicantSearchDB();

            if (Session[General.TAId] == null)
            {
                _taapplicantsearch.TAAppSeaId = 0;
            }
            else
            {
                _taapplicantsearch.TAAppSeaId = Convert.ToInt64(Session[General.TAId].ToString());
            }

            if (Session[General.UserId] == null)
            {
                _taapplicantsearch.RefCEUserId = 0;
                _taapplicantsearch.Name = txtUserName.Text.ToUpper();
                _taapplicantsearch.EmailAddress = txtUserEmail.Text.Trim();
                _taapplicantsearch.MobileNum = txtMobileNo.GetPhoneNo();
            }
            else
            {
                _taapplicantsearch.RefCEUserId = Convert.ToInt64(Session[General.UserId].ToString());
                _taapplicantsearch.Name = Session[General.UserName].ToString();
                _taapplicantsearch.EmailAddress = Session[General.UserEmail].ToString();
                _taapplicantsearch.MobileNum = Session[General.UserPhoneNo].ToString();
            }

            _taapplicantsearch.PlanType = "IND";
            _taapplicantsearch.TripType = "S";
            _taapplicantsearch.CountryID = countryid;
            _taapplicantsearch.AreaID = areaid;
            _taapplicantsearch.CoverageLevel = coveragelevel;
            _taapplicantsearch.Duration = duration;
            _taapplicantsearch.StartDate = startdate;
            _taapplicantsearch.EndDate = enddate;
            _taapplicantsearch.ChildAge = childage;
            _taapplicantsearch.AdultAge = adultage1;
            _taapplicantsearch.NoOfTravellers = noofadults + noofchilds;
            _taapplicantsearch.TotalPremium = 0;

            _taapplicantsearch.NoofAdults = noofadults;
            _taapplicantsearch.DOBAdult1 = dobadult1;
            _taapplicantsearch.DOBAdult2 = dobadult2;
            _taapplicantsearch.DOBAdult3 = dobadult3;
            _taapplicantsearch.DOBAdult4 = dobadult4;
            _taapplicantsearch.NoofChilds = noofchilds;
            _taapplicantsearch.DOBChild1 = dobchild1;
            _taapplicantsearch.DOBChild2 = dobchild2;
            _taapplicantsearch.DOBChild3 = dobchild3;
            _taapplicantsearch.DOBChild4 = dobchild4;
            _taapplicantsearch.DOBChild5 = dobchild5;
            _taapplicantsearch.DOBChild6 = dobchild6;

            _taapplicantsearch.ViewedDetailId = Convert.ToInt64(Session[General.ViewedDetailsId].ToString());

            _taapplicantsearch.Info1 = "0";
            Int64 _result = _taapplicantsearchdb.Insert(_taapplicantsearch);

            if (_result > 0)
            {
                Session["TripType"] = "S";
                Session[General.TAId] = _result.ToString();

                if (Session[General.UserId] == null)
                {
                    Session[General.TAPersonnelId] = _taapplicantsearch.RefCEUserId.ToString();
                    Session[General.TAUserName] = txtFullName.Text.ToUpper();
                    Session[General.TAPhoneNo] = txtMobileNo.GetPhoneNo().ToString();
                    Session[General.TAEmail] = txtUserEmail.Text.Trim();
                }

                Int64 TAAppSeaId = Convert.ToInt64(Session[General.TAId].ToString());
                string Status = "2";
                Int64 _updateresult = _taapplicantsearchdb.UpdateStatus(TAAppSeaId, Status);
                if (_updateresult > 0)
                {

                    //Response.Redirect("../travel-insurance/taresultsquotesone.aspx");
                    //Response.Redirect("../travel-insurance/results.aspx");
                    Response.Redirect("../travel-insurance/results-details.aspx");
                }
            }

            LogUserViewedHistory();
        }
    }

    protected void btnUserInfo_Click(object sender, EventArgs e)
    {
        Page.Validate("userinfo");
        ChangeValidationEffectServerSideUserInfo("userinfo");
        if (Page.IsValid)
        {
            //if (Session[General.TAId] != null)
            //{
            //    Cache.Remove("TAResultsQuotes" + Session[General.TAId].ToString());
            //}

            Int64 countryid = 0;
            Int64 areaid = 0;
            string coveragelevel = "S";
            Int32 duration = 0;
            DateTime startdate = new DateTime(1900, 1, 1);
            DateTime enddate = new DateTime(1900, 1, 1);
            Int32 childage = 0;
            Int32 adultage1 = 0;
            Int32 adultage2 = 0;
            Int32 adultage3 = 0;
            Int32 adultage4 = 0;

            Int32 noofadults = 0;
            DateTime dobadult1 = CE.Global.General.GetUTCDateTime();
            DateTime dobadult2 = CE.Global.General.GetUTCDateTime();
            DateTime dobadult3 = CE.Global.General.GetUTCDateTime();
            DateTime dobadult4 = CE.Global.General.GetUTCDateTime();
            Int32 noofchilds = 0;
            DateTime dobchild1 = CE.Global.General.GetUTCDateTime();
            DateTime dobchild2 = CE.Global.General.GetUTCDateTime();
            DateTime dobchild3 = CE.Global.General.GetUTCDateTime();
            DateTime dobchild4 = CE.Global.General.GetUTCDateTime();
            DateTime dobchild5 = CE.Global.General.GetUTCDateTime();
            DateTime dobchild6 = CE.Global.General.GetUTCDateTime();


            DateTime dtout = Convert.ToDateTime(outbounddate);
            DateTime dtin = Convert.ToDateTime(inbounddate);


            adultage1 = ComputeAge(userBirthday.GetDate());
            dobadult1 = userBirthday.GetDate();
            noofadults = 1;
            noofchilds = 0;
            coveragelevel = "S";

            //Scenario 1
            countryid = Convert.ToInt64(incountryid.Value.Trim());

            duration = ComputeDuration(dtout, dtin);
            startdate = dtout;
            enddate = dtin;

            string[] customerage = { adultage1.ToString(), adultage2.ToString(), adultage3.ToString(), adultage4.ToString() };
            Session[General.TACustomerAge] = customerage;

            TAApplicantSearch _taapplicantsearch = new TAApplicantSearch();
            TAApplicantSearchDB _taapplicantsearchdb = new TAApplicantSearchDB();

            if (Session[General.TAId] == null)
            {
                _taapplicantsearch.TAAppSeaId = 0;
            }
            else
            {
                _taapplicantsearch.TAAppSeaId = Convert.ToInt64(Session[General.TAId].ToString());
            }

            if (Session[General.UserId] == null)
            {
                _taapplicantsearch.RefCEUserId = 0;
                _taapplicantsearch.Name = txtUserName.Text.ToUpper();
                _taapplicantsearch.EmailAddress = txtUserEmail.Text.Trim();
                _taapplicantsearch.MobileNum = txtMobileNo.GetPhoneNo();
            }
            else
            {
                _taapplicantsearch.RefCEUserId = Convert.ToInt64(Session[General.UserId].ToString());
                _taapplicantsearch.Name = Session[General.UserName].ToString();
                _taapplicantsearch.EmailAddress = Session[General.UserEmail].ToString();
                _taapplicantsearch.MobileNum = Session[General.UserPhoneNo].ToString();
            }

            _taapplicantsearch.PlanType = "IND";
            _taapplicantsearch.TripType = "S";
            _taapplicantsearch.CountryID = countryid;
            _taapplicantsearch.AreaID = areaid;
            _taapplicantsearch.CoverageLevel = coveragelevel;
            _taapplicantsearch.Duration = duration;
            _taapplicantsearch.StartDate = startdate;
            _taapplicantsearch.EndDate = enddate;
            _taapplicantsearch.ChildAge = childage;
            _taapplicantsearch.AdultAge = adultage1;
            _taapplicantsearch.NoOfTravellers = noofadults + noofchilds;
            _taapplicantsearch.TotalPremium = 0;

            _taapplicantsearch.NoofAdults = noofadults;
            _taapplicantsearch.DOBAdult1 = dobadult1;
            _taapplicantsearch.DOBAdult2 = dobadult2;
            _taapplicantsearch.DOBAdult3 = dobadult3;
            _taapplicantsearch.DOBAdult4 = dobadult4;
            _taapplicantsearch.NoofChilds = noofchilds;
            _taapplicantsearch.DOBChild1 = dobchild1;
            _taapplicantsearch.DOBChild2 = dobchild2;
            _taapplicantsearch.DOBChild3 = dobchild3;
            _taapplicantsearch.DOBChild4 = dobchild4;
            _taapplicantsearch.DOBChild5 = dobchild5;
            _taapplicantsearch.DOBChild6 = dobchild6;

            _taapplicantsearch.ViewedDetailId = Convert.ToInt64(Session[General.ViewedDetailsId].ToString());

            _taapplicantsearch.Info1 = "0";
            Int64 _result = _taapplicantsearchdb.Insert(_taapplicantsearch);

            if (_result > 0)
            {
                Session["TripType"] = "S";
                Session[General.TAId] = _result.ToString();

                if (Session[General.UserId] == null)
                {
                    Session[General.TAPersonnelId] = _taapplicantsearch.RefCEUserId.ToString();
                    Session[General.TAUserName] = txtFullName.Text.ToUpper();
                    Session[General.TAPhoneNo] = txtMobileNo.GetPhoneNo().ToString();
                    Session[General.TAEmail] = txtUserEmail.Text.Trim();
                }

                Int64 TAAppSeaId = Convert.ToInt64(Session[General.TAId].ToString());
                string Status = "2";
                Int64 _updateresult = _taapplicantsearchdb.UpdateStatus(TAAppSeaId, Status);
                if (_updateresult > 0)
                {
                    //Response.Redirect("../travel-insurance/taresultsquotesone.aspx");
                    //Response.Redirect("../travel-insurance/results.aspx");
                    Response.Redirect("../travel-insurance/results-details.aspx");
                }
            }

            LogUserViewedHistory();
        }
    }

    private void ChangeValidationEffectServerSideUserInfo(string strValidationGroup)
    {
        if (rfvUserName.Enabled && rfvUserName.ValidationGroup == strValidationGroup)
        {
            rfvUserName.Validate();
            if (rfvUserName.IsValid == false)
            {
                txtUserName.ControlStyle.CssClass = "validationError";
            }
            else
            {
                txtUserName.ControlStyle.CssClass = "";
            }
        }
        else
        {
            txtUserName.ControlStyle.CssClass = "";
        }

        if (revUsername.Enabled && revUsername.ValidationGroup == strValidationGroup)
        {
            if (rfvUserName.IsValid)
            {
                revUsername.Validate();
                if (revUsername.IsValid == false)
                {
                    txtUserName.ControlStyle.CssClass = "validationError";
                }
                else
                {
                    txtUserName.ControlStyle.CssClass = "";
                }
            }
        }
        else
        {
            txtUserName.ControlStyle.CssClass = "";
        }

        //Email Address
        if (rfvUserEmail.Enabled && rfvUserEmail.ValidationGroup == strValidationGroup)
        {
            rfvUserEmail.Validate();
            if (rfvUserEmail.IsValid == false)
            {
                txtUserEmail.ControlStyle.CssClass = "validationError";
            }
            else
            {
                txtUserEmail.ControlStyle.CssClass = "";
            }
        }
        else
        {
            txtUserEmail.ControlStyle.CssClass = "";
        }

        if (revUserEmail.Enabled && revUserEmail.ValidationGroup == strValidationGroup)
        {
            if (rfvUserEmail.IsValid)
            {
                revUserEmail.Validate();
                if (revUserEmail.IsValid == false)
                {
                    txtUserEmail.ControlStyle.CssClass = "validationError";
                }
                else
                {
                    txtUserEmail.ControlStyle.CssClass = "";
                }
            }
        }
        else
        {
            txtUserEmail.ControlStyle.CssClass = "";
        }

        userBirthday.ChangeValidationEffectServerSide(strValidationGroup);
        txtMobileNo.ChangeValidationEffectServerSide(strValidationGroup);

    }

    private int ComputeAge(DateTime dtBirth)
    {
        int Age = 0;

        DateTime now = CE.Global.General.GetUTCDateTime();// DateTime.Today;
        Age = now.Year - dtBirth.Year;
        // subtract another year if we're before the birthday in the current year
        if (now.Month < dtBirth.Month || (now.Month == dtBirth.Month && now.Day < dtBirth.Day))
            --Age;

        return Age;
    }

    private int ComputeDuration(DateTime dtFrom, DateTime dtTo)
    {
        int TripDuration = 0;
        TripDuration = Convert.ToInt32(dtTo.Subtract(dtFrom).TotalDays.ToString());
        TripDuration = TripDuration + 1;

        return TripDuration;
    }
    protected void getFlightResult_step1()
    {
        string[] sessionparams = (string[])Session["wegosearchparams"];

        string _strOriginPlace = sessionparams[0].ToString();
        string _strDestinationPlace = sessionparams[1].ToString();
        string _strOutboundDate = sessionparams[8].Split('/')[2] + "-" + sessionparams[8].Split('/')[1] + "-" + sessionparams[8].Split('/')[0];
        string _strInboundDate = "";
        if(sessionparams[9].ToString() != "")
            _strInboundDate = sessionparams[9].Split('/')[2] + "-" + sessionparams[9].Split('/')[1] + "-" + sessionparams[9].Split('/')[0];
        string _strClass = "Economy";
        string _strAdult = sessionparams[4].ToString();
        string _strChild = sessionparams[10].ToString();
        string _strInfant = "0";

        // Create a request using a URL that can receive a post. 
        WebRequest request = WebRequest.Create("http://partners.api.skyscanner.net/apiservices/pricing/v1.0");
        // Set the Method property of the request to POST.
        request.Method = "POST";
        // Create POST data and convert it to a byte array.
        string postData = "apikey=ce546556254256234475323023578300&country=SG&currency=SGD&locale=en-GB&originplace=" +
            _strOriginPlace + "&destinationplace=" + _strDestinationPlace + "&outbounddate=" + _strOutboundDate;

        if (triptype == "roundTrip")
        {
            postData += "&inbounddate=" + _strInboundDate;
        }

        postData += "&locationschema=Iata&cabinclass=" + _strClass + "&adults=" + _strAdult + "&children=" +
            _strChild + "&infants=" + _strInfant;

        byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        // Set the ContentType property of the WebRequest.
        request.ContentType = "application/x-www-form-urlencoded";
        // Set the ContentLength property of the WebRequest.
        request.ContentLength = byteArray.Length;
        // Get the request stream.
        Stream dataStream = request.GetRequestStream();
        // Write the data to the request stream.
        dataStream.Write(byteArray, 0, byteArray.Length);
        // Close the Stream object.
        dataStream.Close();
        // Get the response.
        WebResponse response = request.GetResponse();
        // Display the status.
        //Console.WriteLine(((HttpWebResponse)response).StatusDescription);

        //Label1.Text = response.Headers["Location"] + "<br>";
        response.Close();
        Cache["APISession"] = response.Headers["Location"];
        //Label2.Text = response.Headers["Location"];

        Timer1.Enabled = true;
    }
    protected DataTable getFlightResult_step2()
    {
        DataTable result = new DataTable();
        bool _isPending = true;
        SkyscannerDataInfo _objSkyscannerDataInfo = new SkyscannerDataInfo();
        try
        {
            //do
            //{
                string _strAPISession = Cache["APISession"].ToString();

                string _strSort = "price";
                string getData = "?apikey=ce546556254256234475323023578300&sorttype=" + _strSort + "&sortorder=asc";

                WebRequest request = null;
                request = WebRequest.Create(_strAPISession + getData);
                request.Method = "GET";
                WebResponse response = request.GetResponse();
                // Get the stream containing content returned by the server.
                Stream dataStream = response.GetResponseStream();
                // Open the stream using a StreamReader for easy access.
                StreamReader reader = new StreamReader(dataStream);
                // Read the content.
                string responseFromServer = reader.ReadToEnd();
                //// Display the content.
                //Label1.Text = responseFromServer;
                // Clean up the streams.
                reader.Close();
                dataStream.Close();

                response.Close();

                _objSkyscannerDataInfo = JsonConvert.DeserializeObject<SkyscannerDataInfo>(responseFromServer);
                if (_objSkyscannerDataInfo.Status == "UpdatesComplete")
                {
                    Timer1.Enabled = false;
                    imgLoading.Visible = false;
                    //ScriptManager.RegisterStartupScript(this, GetType(), "displayalertmessage", "hideLoading();", true);
                    _isPending = false;
                    divAirlineLoading.Visible = false;
                    cblCarriers.DataSource = _objSkyscannerDataInfo.Carriers.OrderBy(o => o.Name).ToList();
                    cblCarriers.DataBind();
                    foreach (ListItem item in cblCarriers.Items)
                    {
                        item.Selected = true;
                    }
                }
                Cache["FlightList"] = _objSkyscannerDataInfo;
                result = ToDataTable(_objSkyscannerDataInfo.Itineraries);

                lblFlightResult.Text = _objSkyscannerDataInfo.Status + ", " + Session["count"].ToString();
            //} while (_isPending);
            //Label1.Text = _objSkyscannerDataInfo.Itineraries.Count.ToString() + " records - " + _objSkyscannerDataInfo.Status;
        }
        catch (Exception)
        {

        }

        return result;
    }

    public static DataTable ToDataTable<T>(List<T> items)
    {
        DataTable dataTable = new DataTable(typeof(T).Name);

        //Get all the properties
        System.Reflection.PropertyInfo[] Props = typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
        foreach (System.Reflection.PropertyInfo prop in Props)
        {
            //Setting column names as Property names
            dataTable.Columns.Add(prop.Name);
        }
        foreach (T item in items)
        {
            var values = new object[Props.Length];
            for (int i = 0; i < Props.Length; i++)
            {
                //inserting property values to datatable rows
                values[i] = Props[i].GetValue(item, null);
            }
            dataTable.Rows.Add(values);
        }
        //put a breakpoint here and check datatable
        return dataTable;
    }
    protected string getBookingDetails_step1(Itineraries _objItineraries, int AgentID)
    {
        // Create a request using a URL that can receive a post. 
        WebRequest request = WebRequest.Create("http://partners.api.skyscanner.net" + _objItineraries.BookingDetailsLink.Uri);
        // Set the Method property of the request to POST.
        request.Method = "PUT";
        // Create POST data and convert it to a byte array.
        string postData = "apikey=ce546556254256234475323023578300&outboundlegid=" + _objItineraries.OutboundLegId +
            "&inboundlegid=" + _objItineraries.InboundLegId;
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        // Set the ContentType property of the WebRequest.
        request.ContentType = "application/x-www-form-urlencoded";
        // Set the ContentLength property of the WebRequest.
        request.ContentLength = byteArray.Length;
        // Get the request stream.
        Stream dataStream = request.GetRequestStream();
        // Write the data to the request stream.
        dataStream.Write(byteArray, 0, byteArray.Length);
        // Close the Stream object.
        dataStream.Close();
        // Get the response.
        WebResponse response = request.GetResponse();
        // Display the status.
        //Console.WriteLine(((HttpWebResponse)response).StatusDescription);

        response.Close();

        return getBookingDetails_step2(response.Headers["Location"], AgentID);
    }
    protected string getBookingDetails_step2(string _strResponseURL, int AgentID)
    {
        string result = "";
        try
        {
            SkyscannerDataInfo _objSkyscannerDataInfo = new SkyscannerDataInfo();

            string getData = "?apikey=ce546556254256234475323023578300";

            WebRequest request = null;
            request = WebRequest.Create(_strResponseURL + getData);
            request.Method = "GET";
            WebResponse response = request.GetResponse();
            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            //// Display the content.
            //Label1.Text = responseFromServer;
            // Clean up the streams.
            reader.Close();
            dataStream.Close();

            response.Close();

            BookingDetails _objBookingDetails = JsonConvert.DeserializeObject<BookingDetails>(responseFromServer);
            foreach (BookingOptions item in _objBookingDetails.BookingOptions)
            {
                if (item.BookingItems[0].AgentID == AgentID)
                    result = item.BookingItems[0].Deeplink;
            }
        }
        catch (Exception ex)
        {

        }
        return result;
    }
    protected void Timer1_Tick(object sender, EventArgs e)
    {
        if (Session["count"] == null)
            Session["count"] = timercount;
        Session["count"] = int.Parse(Session["count"].ToString()) + 1;
        GetFlightDetails();
    }
    protected void cblCarriers_SelectedIndexChanged(object sender, EventArgs e)
    {
        SkyscannerDataInfo _objSkyscannerDataInfoFiltered = new SkyscannerDataInfo();
        _objSkyscannerDataInfoFiltered.Itineraries = new List<Itineraries>();
        SkyscannerDataInfo _objSkyscannerDataInfo = Cache["FlightList"] as SkyscannerDataInfo;
        List<int> _ltSelectedCarriers = new List<int>();
        foreach (ListItem item in cblCarriers.Items)
        {
            if (item.Selected)
                _ltSelectedCarriers.Add(int.Parse(item.Value));
        }

        foreach (Itineraries item in _objSkyscannerDataInfo.Itineraries)
        {
            PageNumber = 0;
            bool _isCarrierExist = false;
            Legs _objOutboundLeg = _objSkyscannerDataInfo.Legs.Find(x => x.Id == item.OutboundLegId);
            Legs _objInboundLeg = _objSkyscannerDataInfo.Legs.Find(x => x.Id == item.InboundLegId);

            foreach (int carrierid in _objOutboundLeg.Carriers)
            {
                foreach (int selectedcarrierid in _ltSelectedCarriers)
                {
                    if (carrierid == selectedcarrierid)
                        _isCarrierExist = true;
                }
            }

            if (_isCarrierExist)
                _objSkyscannerDataInfoFiltered.Itineraries.Add(item);
            else
            {
                foreach (int carrierid in _objInboundLeg.Carriers)
                {
                    foreach (int selectedcarrierid in _ltSelectedCarriers)
                    {
                        if (carrierid == selectedcarrierid)
                            _isCarrierExist = true;
                    }
                }
                if (_isCarrierExist)
                    _objSkyscannerDataInfoFiltered.Itineraries.Add(item);
            }
        }
        Cache["FlightListFiltered"] = _objSkyscannerDataInfoFiltered;
        GetFlightDetails(_objSkyscannerDataInfoFiltered);
    }
    protected void dlTAResultsInsurer_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            if (DataBinder.Eval(e.Item.DataItem, "AnnualPremium").ToString() == "0.01")
            {
                Image imgCompanyLogo = (Image)e.Item.FindControl("imgCompanyLogo");
                imgCompanyLogo.Visible = false;
            }
            else
            {
                Image imgCompanyLogo = (Image)e.Item.FindControl("imgCompanyLogo");
                string providercompanyid = DataBinder.Eval(e.Item.DataItem, "providercompanyid").ToString();
                string imageurl = "~/images/public/logo/";

                if (providercompanyid == "23")
                {
                    imageurl += "hsbc_xs.png";
                }
                else if (providercompanyid == "24")
                {
                    imageurl += "rsa_xs.png";
                }
                else if (providercompanyid == "29")
                {
                    imageurl += "liberty_xs.png";
                }
                else if (providercompanyid == "30")
                {
                    imageurl += "etiqa_xs.png";
                }
                else if (providercompanyid == "31")
                {
                    imageurl += "chartis_xs.png";
                }
                else if (providercompanyid == "34")
                {
                    imageurl += "chinataiping_xs.png";
                }
                else if (providercompanyid == "35")
                {
                    imageurl += "eq_xs.png";
                }
                else if (providercompanyid == "36")
                {
                    imageurl += "ace_xs.png";
                }
                else if (providercompanyid == "37")
                {
                    imageurl += "1cover_xs.png";
                }
                else if (providercompanyid == "38")
                {
                    imageurl += "directasia_xs.png";
                }


                imgCompanyLogo.ImageUrl = imageurl;
            }

            if (e.Item.ItemIndex == 0)
                e.Item.CssClass = "packone tr";
            else if (e.Item.ItemIndex == 1)
                e.Item.CssClass = "packtwo tr";
            else if (e.Item.ItemIndex == 2)
                e.Item.CssClass = "packthree tr";
            else if (e.Item.ItemIndex == 3)
                e.Item.CssClass = "packfour tr";
            else if (e.Item.ItemIndex == 4)
                e.Item.CssClass = "packfive tr";
            else if (e.Item.ItemIndex == 5)
                e.Item.CssClass = "packsix tr";
            else if (e.Item.ItemIndex == 6)
                e.Item.CssClass = "packseven tr";
            else if (e.Item.ItemIndex == 7)
                e.Item.CssClass = "packeight tr";
        }
    }
    protected void dlTAResultsInsurer_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName.Equals("Compare"))
        {
            //Sakthi on 07 Mar 2011 -- start
            //TAApplicantSearchDB _taapplicantsearchdb = new TAApplicantSearchDB();
            //Int64 TAAppSeaId = 0;
            //string Status = "0";
            //if (Session[General.TAId] == null)
            //{
            //    TAAppSeaId = 0;
            //}
            //else
            //{
            //    TAAppSeaId = Convert.ToInt64(Session[General.TAId].ToString());
            //}
            //Status = "2";
            //Int64 _result = _taapplicantsearchdb.UpdateStatus(TAAppSeaId, Status);
            //Sakthi on 07 Mar 2011 -- End

            //Response.Redirect("~/travel_insurance/TAresultsquotesOne.aspx");
            //Response.Redirect("../travel_insurance/travel_quote.aspx");

            //mpeUserInfo.Show();

            //if (Session[General.TAId] != null)
            //{
            //    Cache.Remove("TAResultsQuotes" + Session[General.TAId].ToString());
            //}

            Int64 countryid = 0;
            Int64 areaid = 0;
            string coveragelevel = "S";
            Int32 duration = 0;
            DateTime startdate = new DateTime(1900, 1, 1);
            DateTime enddate = new DateTime(1900, 1, 1);
            Int32 childage = 0;
            Int32 adultage1 = 0;
            Int32 adultage2 = 0;
            Int32 adultage3 = 0;
            Int32 adultage4 = 0;

            Int32 noofadults = 0;
            DateTime dobadult1 = CE.Global.General.GetUTCDateTime();
            DateTime dobadult2 = CE.Global.General.GetUTCDateTime();
            DateTime dobadult3 = CE.Global.General.GetUTCDateTime();
            DateTime dobadult4 = CE.Global.General.GetUTCDateTime();
            Int32 noofchilds = 0;
            DateTime dobchild1 = CE.Global.General.GetUTCDateTime();
            DateTime dobchild2 = CE.Global.General.GetUTCDateTime();
            DateTime dobchild3 = CE.Global.General.GetUTCDateTime();
            DateTime dobchild4 = CE.Global.General.GetUTCDateTime();
            DateTime dobchild5 = CE.Global.General.GetUTCDateTime();
            DateTime dobchild6 = CE.Global.General.GetUTCDateTime();


            DateTime dtout = Convert.ToDateTime(outbounddate);
            DateTime dtin = Convert.ToDateTime(inbounddate);

            //removed popup
            //adultage1 = ComputeAge(userBirthday.GetDate());
            //dobadult1 = userBirthday.GetDate();

            adultage1 = 25; //default
            dobadult1 = CE.Global.General.GetUTCDateTime().AddYears(-25);//default

            noofadults = 1;
            noofchilds = 0;
            coveragelevel = "S";

            //Scenario 1
            countryid = Convert.ToInt64(incountryid.Value.Trim());

            duration = ComputeDuration(dtout, dtin);
            startdate = dtout;
            enddate = dtin;

            string[] customerage = { adultage1.ToString(), adultage2.ToString(), adultage3.ToString(), adultage4.ToString() };
            Session[General.TACustomerAge] = customerage;

            TAApplicantSearch _taapplicantsearch = new TAApplicantSearch();
            TAApplicantSearchDB _taapplicantsearchdb = new TAApplicantSearchDB();

            if (Session[General.TAId] == null)
            {
                _taapplicantsearch.TAAppSeaId = 0;
            }
            else
            {
                _taapplicantsearch.TAAppSeaId = Convert.ToInt64(Session[General.TAId].ToString());
            }

            if (Session[General.UserId] == null)
            {
                _taapplicantsearch.RefCEUserId = 0;
                _taapplicantsearch.Name = txtUserName.Text.ToUpper();
                _taapplicantsearch.EmailAddress = txtUserEmail.Text.Trim();
                _taapplicantsearch.MobileNum = txtMobileNo.GetPhoneNo();
            }
            else
            {
                _taapplicantsearch.RefCEUserId = Convert.ToInt64(Session[General.UserId].ToString());
                _taapplicantsearch.Name = Session[General.UserName].ToString();
                _taapplicantsearch.EmailAddress = Session[General.UserEmail].ToString();
                _taapplicantsearch.MobileNum = Session[General.UserPhoneNo].ToString();
            }

            _taapplicantsearch.PlanType = "IND";
            _taapplicantsearch.TripType = "S";
            _taapplicantsearch.CountryID = countryid;
            _taapplicantsearch.AreaID = areaid;
            _taapplicantsearch.CoverageLevel = coveragelevel;
            _taapplicantsearch.Duration = duration;
            _taapplicantsearch.StartDate = startdate;
            _taapplicantsearch.EndDate = enddate;
            _taapplicantsearch.ChildAge = childage;
            _taapplicantsearch.AdultAge = adultage1;
            _taapplicantsearch.NoOfTravellers = noofadults + noofchilds;
            _taapplicantsearch.TotalPremium = 0;

            _taapplicantsearch.NoofAdults = noofadults;
            _taapplicantsearch.DOBAdult1 = dobadult1;
            _taapplicantsearch.DOBAdult2 = dobadult2;
            _taapplicantsearch.DOBAdult3 = dobadult3;
            _taapplicantsearch.DOBAdult4 = dobadult4;
            _taapplicantsearch.NoofChilds = noofchilds;
            _taapplicantsearch.DOBChild1 = dobchild1;
            _taapplicantsearch.DOBChild2 = dobchild2;
            _taapplicantsearch.DOBChild3 = dobchild3;
            _taapplicantsearch.DOBChild4 = dobchild4;
            _taapplicantsearch.DOBChild5 = dobchild5;
            _taapplicantsearch.DOBChild6 = dobchild6;

            _taapplicantsearch.ViewedDetailId = Convert.ToInt64(Session[General.ViewedDetailsId].ToString());

            _taapplicantsearch.Info1 = "0";
            Int64 _result = _taapplicantsearchdb.Insert(_taapplicantsearch);

            if (_result > 0)
            {
                Session["TripType"] = "S";
                Session[General.TAId] = _result.ToString();

                if (Session[General.UserId] == null)
                {
                    Session[General.TAPersonnelId] = _taapplicantsearch.RefCEUserId.ToString();
                    Session[General.TAUserName] = txtFullName.Text.ToUpper();
                    Session[General.TAPhoneNo] = txtMobileNo.GetPhoneNo().ToString();
                    Session[General.TAEmail] = txtUserEmail.Text.Trim();
                }

                Int64 TAAppSeaId = Convert.ToInt64(Session[General.TAId].ToString());
                string Status = "2";
                Int64 _updateresult = _taapplicantsearchdb.UpdateStatus(TAAppSeaId, Status);
                if (_updateresult > 0)
                {
                    //Response.Redirect("../travel-insurance/taresultsquotesone.aspx");
                    //Response.Redirect("../travel-insurance/results.aspx");
                    Response.Redirect("../travel-insurance/results-details.aspx");
                }
            }

            LogUserViewedHistory();
        }
    }
}
